使用 'this' 指针返回 class 成员指针变量的值
Returning the value of a class member pointer variable using 'this' pointer
我的方案是,我想 return 使用 this
指针 class 成员变量 m_ptr
的值。
我试过的是,
#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
这很好。
我现在要做的是,
我想使用 this
指针将 getValue
函数修改为 return 指针变量 m_ptr
的值,如下所示。 (只写了getValue
函数)
int getValue(){
return this->(*m_ptr);
}
但这会抛出错误,
[Error] expected unqualified-id before '(' token
我是这个c++的初学者,我不明白这个错误的真正原因。在这里解释我做错了什么会很有帮助。
间接运算符位置错误。 this->m_ptr
访问成员是正确的,并通过该指针间接访问,将间接运算符放在左侧:
return *this->m_ptr;
我的方案是,我想 return 使用 this
指针 class 成员变量 m_ptr
的值。
我试过的是,
#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
这很好。
我现在要做的是,
我想使用 this
指针将 getValue
函数修改为 return 指针变量 m_ptr
的值,如下所示。 (只写了getValue
函数)
int getValue(){
return this->(*m_ptr);
}
但这会抛出错误,
[Error] expected unqualified-id before '(' token
我是这个c++的初学者,我不明白这个错误的真正原因。在这里解释我做错了什么会很有帮助。
间接运算符位置错误。 this->m_ptr
访问成员是正确的,并通过该指针间接访问,将间接运算符放在左侧:
return *this->m_ptr;