In the following code, I set a static variable of a class is private. Then I initialize its value as for a public static member of a class. However, a compiler error has been occurred. Please help me clarify this issue.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
class A{
private:
staticint num;
public:
A(){
cout <<"A new object of the class has been created!"<<endl;
num++;
}
};
int A::num=0;
int main(){
A a_1;
A a_2;
cout<<A::num<<endl;
}
The message after compiling:
||=== Build: Debug in class (compiler: GNU GCC Compiler) ===|
D:\C++\Learning\project\class\main.cpp||In function 'int main()':| D:\C++\Learning\project\class\main.cpp|12|error: 'int A::num' is private|
D:\C++\Learning\project\class\main.cpp|16|error: within this context|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
Line 12 is fine. The problem is when you try to access the private variable from main(). If you want to provide read-only access to functions outside the class you could create static getter function.
1 2 3 4 5
// in the public area of class A
staticint getNum() { return num; }
// in function main()
cout << A::getNum() << endl;