c++中this指针使用bug
1.bug代码:
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
是指针,访问它所指向对象的成员变量或成员函数时,必须用箭头运算符->
,而不是点运算符.
。
正确写法:
this->num = x;
为什么不能用点运算符 .
?
.
用于对象本身访问成员:Test<int> obj; obj.num = 5; // 对象用点运算符
->
用于指针访问成员:Test<int>* p = &obj; p->num = 5; // 指针用箭头运算符
this
是Test* 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
。