For some strange reason g++ (versions 4.5.0 and 4.5.2) cannot compile this code:
bool somefunc() {
return false;
}
class C {
public:
static const int a = 0;
static const int b = 1;
};
class myclass {
public:
int check() {
return somefunc() ? C::a : C::b;
// if(somefunc()) return C::a; else return C::b;
}
};
int main() {
myclass obj;
obj.check();
return 0;
}
It gives me this error:
/tmp/ccyvvTUy.o:/home/mati/test.cpp:14: undefined reference to `C::a'
/tmp/ccyvvTUy.o:/home/mati/test.cpp:14: undefined reference to `C::b'
collect2: ld returned 1 exit status
What's strange if I change problematic line to the commented line it compiles fine. Is it something wrong with my code and something I don't understand about C++ or is it just a bug in G++ ?
There is an ongoing debate on whether this code is actually legal or not.
Either way, according to some readings the constants actually do need to be defined before usage, not just declared. That is,
class C {
public:
static const int a = 0;
static const int b = 1;
};
const int C::a;
const int C::b;
Or just use the enum
hack that was used to accomodate older compilers (but which may after all be the only legal way):
class C {
public:
enum { a = 0, b = 1 };
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With