[英]Why can't a static data member has the same name with non-static data member?
#include<stdio.h>
#include<vector>
#include<iostream>
using namespace std;
int x = 1;
class foo
{
public:
foo()
{
x = 3;
}
static int x;
void bar() const
{
cout << x << endl;
}
int x;
};
int foo::x = 2;
int main()
{
cout << "Hello, world!" << endl;
return 0;
}
here's the compiler output: 这是编译器的输出:
test.cc:19:9: error: ‘int foo::x’ conflicts with a previous declaration
int x;
^
test.cc:14:16: note: previous declaration ‘int foo::x’
static int x;
They can't have the same name because which one would you mean when you refer to x
in a non-static method? 它们不能具有相同的名称,因为当您以非静态方法引用x
时,您指的是哪个?
The language designers could have decided to allow it, eg to prefer the non-static one or the reverse. 语言设计者可以决定允许它,例如更喜欢非静态的或相反的。 But personally I'm glad they didn't. 但是我个人很高兴他们没有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.