Skip to main content
Remove superfluous code, add full error message from gcc 11.2, fix grammar, adjust tags
Source Link
Brian61354270
  • 13.4k
  • 6
  • 31
  • 52

An error "Invalid use of non-static data member" when initializing a static data member of classfrom global variable

class A {
    private:int x;
    static int i;
};


int x int= x;10;
int A::i = x;

When I compile the code above, it get the error

<source>:8:12: error: invalid use of non-static Adata a;member 'A::x'
    8 | int A::i static= intx;
  i;
    public:
|        A(int y){   ^
<source>:2:9: note: declared here
    2 |     std::cout<<y<<std::endl;int x;
      |  }
};
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 aboutWhat's causing this problem, Could anyone give me helperror?

An error of initializing a static data member of class

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?

"Invalid use of non-static data member" when initializing static member from global variable

class A {
    int x;
    static int i;
};


int x = 10;
int A::i = x;

When I compile the code above, it get the error

<source>:8:12: error: invalid use of non-static data member 'A::x'
    8 | int A::i = x;
      |            ^
<source>:2:9: note: declared here
    2 |     int x;
      |         ^

What's causing this error?

Became Hot Network Question
Source Link
YuCL Lan
  • 193
  • 1
  • 5

An error of initializing a static data member of class

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?