我们无法在具有类本身相同名称的类中声明和定义变量(属性)的原因是什么?例如,这段代码不对(至少在MS VC++中):
class test{
public:
int test;
};
Run Code Online (Sandbox Code Playgroud)
你的代码是合法的,如果MS VC++另有说法,那就错了.
在C++ 11,9.2/16中:
此外,如果类T具有用户声明的构造函数(12.1),则类T的每个非静态数据成员都应具有与T不同的名称.
您的类没有用户声明的构造函数,并且您定义的数据成员是非静态的,因此可以对其进行命名test.如果它是静态的,则9.2/15表示无法命名test,但9.2/15对非静态数据成员一无所知.
在C++ 03中,它是9.2/13和/ 13a,规则是相同的.
如果MS VC++发出警告,那么这可能是合理的.数据成员的效果对C程序员比对C++程序员更有意义:
struct test{
void foo(test &a) { // "test" is a type here
struct test t; // "test is not a type here, "struct test" is
a = t;
}
int test;
};
struct test{
int test;
void foo(struct test &a) { // now "test" is not a type here either
struct test t;
a = t;
}
};
Run Code Online (Sandbox Code Playgroud)