问题描述
我的场景是,我想使用 m_ptr
指针返回类成员变量 this
的值。
我尝试过的是,
#include <iostream>
using namespace std;
class Test{
int *m_ptr;
public:
test():m_ptr(nullptr){
cout<<"Def constr"<<endl;
}
Test(int *a):m_ptr(a){
cout<<"Para constr"<<endl;
}
~test(){
cout<<"Destr "<<endl;
delete m_ptr;
}
int getValue(){
return *m_ptr;
}
};
int main(){
Test obj(new int(34));
cout<<"Value -"<<obj.getValue()<<endl;
return 0;
}
控制台输出是
Para constr
Value -34
Destr
这很好。
我现在要做的是,
我想修改 getValue
函数以使用 m_ptr
指针返回指针变量 this
的值,如下所示。 (仅编写 getValue
函数)
int getValue(){
return this->(*m_ptr);
}
但这会引发错误,
我是这个 C++ 的初学者,我不明白这个错误的实际原因。在这里解释我做错了什么会很有帮助。
解决方法
间接运算符位置错误。 this->m_ptr
访问成员是正确的,通过该指针间接访问,您将间接运算符放在左侧:
return *this->m_ptr;