How to fix undefined reference compiler error

find the error in the following code:

class A { public: static int i; void print() { cout<< i << endl ; } }; int main() { A a; a.print(); } 

I run the code above and I get the “undefined” link to “A :: I.” Why am I getting this error?

+4
source share
2 answers

Since A::i is a member of static , it must be defined outside the class :

 using namespace std; class A { public: static int i; // A::i is declared here. void print() { cout << i << endl; } }; int A::i = 42; // A::i is defined here. 
+12
source

static int i in class A is just a declaration, you need to define it outside the class by adding the operator int A::i = 0;

+7
source

Source: https://habr.com/ru/post/1333550/


All Articles