how to correct it so I can display the static int by
cout<<A::a<<endl;
like in an example below?
#include <iostream>
using namespace std;
class A{
public:
static int a = 0;
};
int main()
{
cout << A::a << endl;
return 0;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Inside the class definition, the static members are only declared and not defined. By default, only definitions have initialization, with the exception that for static constants of integral types the declaration can have the initialization.
The problem in your program is that the static member is used (
std::cout << A::ais odr-use for non-const static member attributes), but you have no definition. You need to define the variable in a single translation unit in your program by adding:(Note that because the static member is not const, you cannot provide an initializer inside the class definition, so you need to remove the
= 0from the declaration in class definition. Also note that you can skip the= valuein the initialization ifvalue == 0, as static initialization will setA::ato 0 before any other initialization)