#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;
}
这里的编译器输出:为什么静态数据成员不能与非静态数据成员具有相同的名称?
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;
它的原理相同,你不能在同一个范围内在一个函数中使用同一个名字的两个变量(如果其中一个是静态的,它们是无关紧要的)。 – eshb
因为否则你不知道哪个是哪个。该计划将不明确。 – EJP