In C ++ Primer 4th 12.6.2, it is recommended to repeat the static variable const outside the class.
However, the code below is in gcc 4.6.3.
#include <iostream>
using namespace std;
class X {
public:
const static int a = 1;
};
int main() {
X x;
cout << x.a << endl;
return 0;
}
Should we reuse it?
PS:
As recommended by Potatoswatter, I added a function to use a constant static member as a reference:
const int X::a;
void test(const int& a) {
cout << a << endl;
}
int main() {
X x;
test(X::a);
return 0;
}
If we did not include const int X::aoutside the class X, it generated an error as shown below
undefined reference to 'X::a'
It is good practice to define a definition outside the class, whether it is constant or not.
source
share