成员函数中能直接用name是因为编译器自动添加this->前缀,等价于this->name;仅当参数或局部变量与成员变量同名时才需显式写this->name以消除歧义。

为什么成员函数里能直接用 name 而不用写 this->name
因为编译器自动把 this 加在了所有非静态成员访问前面。你写 name = "Alice",实际等价于 this->name = "Alice"。只有当局部变量或参数名和成员变量同名时,才必须显式写 this->name 来消除歧义。
常见错误现象:构造函数参数名和成员变量一样,却忘了加 this->,结果赋值没生效:
class Person {
std::string name;
public:
Person(std::string name) { // 参数 name 遮蔽了成员 name
name = name; // 错!这是给参数自己赋值
}
};
正确写法是:
Person(std::string name) : name(name) {} // 推荐:用初始化列表
// 或
Person(std::string name) {
this->name = name; // 显式用 this 指向成员
}
this 指针能被赋值或取地址吗
不能赋值,this 是右值(C++11 起是纯右值),类型是 T* const —— 指针本身不可修改,但指向的对象可修改(除非函数是 const 成员函数)。
常见误操作:
-
this = nullptr;→ 编译错误:无法给this赋值 -
&this→ 错误:不能对右值取地址 -
return this;是合法的,返回当前对象地址,常用于链式调用
例如实现流式接口:
class Counter {
int val = 0;
public:
Counter& inc() { val++; return *this; }
Counter& dec() { val--; return *this; }
};
// 使用:Counter c; c.inc().inc().dec();
在 const 成员函数里,this 的类型是什么
是 const T* const —— 指针不可变,指向的对象也不可变。这意味着你不能通过 this 修改任何非 mutable 成员。
典型场景:调试时想在 const 函数里打印日志,但日志计数器需要更新:
class Cache {
mutable int hit_count = 0; // mutable 允许在 const 函数里修改
public:
int get(int key) const {
hit_count++; // OK
return /* ... */;
}
};
如果漏掉 mutable,hit_count++ 会编译失败,错误信息类似:cannot assign to non-static data member within const member function。
什么时候必须显式使用 this->
除了参数/局部变量遮蔽成员外,模板类中依赖名字查找时也必须加 this->,否则编译器可能无法识别成员是模板参数的成员:
template<typename t>
struct Base {
int value = 42;
};
<p>template<typename t>
struct Derived : Base<t> {
void foo() {
// value++; // 错!value 不被视为依赖名称,查找失败
this->value++; // 正确:显式告诉编译器 value 是基类成员
}
};</t></typename></p></typename>
这个坑只在模板继承中出现,非模板代码里几乎不需要靠 this-> 触发 ADL 或解决查找问题。
容易忽略的是:即使不报错,某些 IDE 或静态分析工具可能因缺少 this-> 而无法正确跳转到成员定义,影响开发体验。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!











