-3

I have a code like this. When run, it's return fault: undefined reference to A::x. How can I fix this?

#include <iostream> using namespace std; class A { private: static int x; public: A(){ } A(int t) { x = t; } static void f() { cout<< A::x; } int f2() { return x; } }; int main() { A::f(); A a; a.f2(); } 
3
  • Linking code from external hosts is not allowed. Minimal, valid and verifiable sample code, that represents your specific problem, must be included as part of the question. Commented Aug 18, 2015 at 1:59
  • 1
    you only declared static variable, static variable also should be defined out side of your class.(i.e) int A::x = some_value; your trying to modify static in your code. Commented Aug 18, 2015 at 1:59
  • tks everyone, i fixed Commented Aug 18, 2015 at 2:25

2 Answers 2

0

You have only declared your static variable, not defined it.

Define it outside of the class using:

int A::x = 0; 
Sign up to request clarification or add additional context in comments.

Comments

0

You need to add

int A::x = 0; //Or any other value 

somewhere outside your class declaration.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.