Home > Mobile >  An error of initializing a static data member of class
An error of initializing a static data member of class

Time:02-07

class A{
    private:
        int x;
        static A a;
        static int  i;
    public:
        A(int y){
            std::cout<<y<<std::endl;
        }
};
int x = 10;
A a(x);
int A::i = x;

I have a problem when I execute the above codes. It shows the “invalid use of non-static data member ‘A::x’”。 I have no idea about this problem, Could anyone give me help?

CodePudding user response:

This is a peculiar language quirk - the scope resolution on the left, in int A::i, affects the lookup scope on the right, so that actually refers to the x member of A.

Either rename one of the variables, or specify the scope of the desired x explicitly:

int A::i = ::x;
  •  Tags:  
  • Related