微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用“this”指针返回类成员指针变量的值

如何解决使用“this”指针返回类成员指针变量的值

我的场景是,我想使用 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);
} 

但这会引发错误

[错误] 预期在 '(' 标记之前为非限定 ID

我是这个 C++ 的初学者,我不明白这个错误的实际原因。在这里解释我做错了什么会很有帮助。

解决方法

间接运算符位置错误。 this->m_ptr 访问成员是正确的,通过该指针间接访问,您将间接运算符放在左侧:

return *this->m_ptr;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。