Solved A question about getting the address of a class static const.
-
#include <iostream>
using namespace std;
class A{
public:
static const int a=3;
};int main(){
cout<<&A::a;
return 0;
}
When I compile the code above. It pops out an error saying: undefined reference to A::a. But I have already initialized a to be 3, So could you please explain it to me? -
@PikaCat
https://stackoverflow.com/questions/18107077/how-to-access-the-address-of-a-static-const-member-of-a-classYou're going to need to add
const int A::a
in the.cpp
, to give it storage. And note that your code does compile, it does not link. Plus, apparently, you're likely usinggcc
because (some?) MSVC does allow what you have written? -
@PikaCat
https://stackoverflow.com/questions/18107077/how-to-access-the-address-of-a-static-const-member-of-a-classYou're going to need to add
const int A::a
in the.cpp
, to give it storage. And note that your code does compile, it does not link. Plus, apparently, you're likely usinggcc
because (some?) MSVC does allow what you have written? -
Thanks:)
-
You can also use
constexpr
instead ofconst
in your example to make it working correctly. -
@Konstantin-Tokarev
You are right, but I am surprised, I thoughtconstexpr
gave you more of a compile-time constant. (I am not a C++ expert.)