繁体   English   中英

为什么静态数据成员不能与非静态数据成员具有相同的名称?

[英]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;
}

这是编译器的输出:

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;

它们不能具有相同的名称,因为当您以非静态方法引用x时,您指的是哪个?

语言设计者可以决定允许它,例如更喜欢非静态的或相反的。 但是我个人很高兴他们没有。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM