简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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