And*_*ndy 11 c++ constructor initialization-list
在编写我的类时,我总是一个好孩子,用m_作为所有成员变量的前缀:
class Test {
int m_int1;
int m_int2;
public:
Test(int int1, int int2) : m_int1(int1), m_int2(int2) {}
};
int main() {
Test t(10, 20); // Just an example
}
Run Code Online (Sandbox Code Playgroud)
然而,最近我忘记这样做了,最后写了:
class Test {
int int1;
int int2;
public:
// Very questionable, but of course I meant to assign ::int1 to this->int1!
Test(int int1, int int2) : int1(int1), int2(int2) {}
};
Run Code Online (Sandbox Code Playgroud)
信不信由你,编译的代码没有错误/警告,并且分配正确!只有在检查我的代码之前进行最后检查时才意识到我做了什么.
我的问题是:为什么我的代码编译?在C++标准中是否允许这样的东西,还是仅仅是编译器聪明的情况?如果您想知道,我使用的是Visual Studio 2008
CB *_*ley 26
是的,它是有效的.成员初始值设定项列表中的名称在构造函数的类的上下文中int1查找,因此查找成员变量的名称.
初始化表达式在构造函数本身的上下文中int1查找,因此找到掩盖成员变量的参数.