c++中this指针使用bug

1.bug代码:

cpp 复制代码
template<typename T>
class Test {
private:
    T num;
public:
    Test() {}

    void setData(const T& x) {
        this.num = x;  // ❌ 这里会报错
    }

    void showData() {
        cout << this->num << endl;
    }
};

2. 报错原因

在 C++ 里:

  • this 是一个指针,它指向当前对象的地址。
  • 既然 this 是指针,访问它所指向对象的成员变量或成员函数时,必须用箭头运算符 -> ,而不是点运算符 .

正确写法

cpp 复制代码
this->num = x;

为什么不能用点运算符 .

  • . 用于对象本身 访问成员:

    复制代码
    Test<int> obj;
    obj.num = 5; // 对象用点运算符
  • -> 用于指针 访问成员:

    复制代码
    Test<int>* p = &obj;
    p->num = 5; // 指针用箭头运算符
  • thisTest* const 类型的指针,所以必须写成 this->num


3. 修正后的代码

复制代码
template<typename T>
class Test {
private:
    T num;
public:
    Test() {}

    void setData(const T& x) {
        this->num = x;  // ✅ 正确写法
    }

    void showData() {
        cout << this->num << endl;
    }
};

4. 另外一种情况:模板类中 this-> 的作用

在模板类里,有时 this-> 还有提示编译器的作用

  • 如果成员依赖于模板参数,编译器需要知道它是类的成员,否则可能无法正确解析。

  • 例如:

    复制代码
    template <typename T>
    struct Base {
        void foo();
    };
    
    template <typename T>
    struct Derived : Base<T> {
        void bar() {
            this->foo(); // 必须用 this->,否则编译器不知道 foo 是基类的成员
        }
    };

    这是因为在模板中,基类的成员名不会自动进入派生类的作用域,需要用 this->Base<T>:: 显式访问。


5. 总结

用法 适用场景
object.member 对象访问成员
pointer->member 指针访问成员
this->member 在类的成员函数中访问当前对象的成员(因为 this 是指针)

一句话解释你这个报错

this 是一个指针,访问成员要用 -> 而不是 .,所以 this.num 应该写成 this->num

相关推荐
K 旺仔小馒头2 小时前
《牛刀小试!C++ string类核心接口实战编程题集》
c++·算法
草莓熊Lotso3 小时前
《吃透 C++ vector:从基础使用到核心接口实战指南》
开发语言·c++·算法
AI视觉网奇8 小时前
rknn yolo11 推理
前端·人工智能·python
gplitems1238 小时前
Gunslinger – Gun Store & Hunting WordPress Theme: A Responsible
开发语言·前端·javascript
wyzqhhhh10 小时前
less和sass
前端·less·sass
2401_8414956411 小时前
【数据结构】红黑树的基本操作
java·数据结构·c++·python·算法·红黑树·二叉搜索树
liu****11 小时前
负载均衡式的在线OJ项目编写(六)
运维·c++·负载均衡·个人开发
青草地溪水旁12 小时前
设计模式(C++)详解——迭代器模式(3)
c++·设计模式·迭代器模式
Nan_Shu_61412 小时前
学习:uniapp全栈微信小程序vue3后台-额外/精彩报错篇
前端·学习·微信小程序·小程序·uni-app·notepad++