static const not const in switch
hello
I have a class with static const attributes, for example:
class foo
{
public:
static const DWORD bar;
}
const DWORD foo::bar = 1;
and now I want to use this constant in switch:
switch
..
case (foo::bar): <-- but it says here that case expression is not constant
..
why?
can I do sth to use such constants in case expression?
my compiler is MSVC2003
Thanks
it works fine that error only comes up when theres no ; after the class def. Did you forget it?
static/class members that are constant intergal types can be defined inside a class, this is very beneficial when doing meta-template programming [grin]
#include <cstddef>struct foo { typedef std::size_t size_type; static const size_type bar = 30;};
no it's not ; , I just forgot about it.
when I have class consisting of 2 files:
"key.h"
class CKey
{
public:
int key;
static const int foo;
};
EOF
"key.cpp"
#include "Key.h"
const int CKey::foo = 1;
EOF
then this code doesn't work:
#include "Key.h"
int main() {
CKey obj;
int k;
switch (obj.key) {
case ( CKey::foo ): <---- error here
k = 4;
break;
}
return 0;
}
EOF
but when I write it all in one file then it works.
It works also when I initialze my static const class attributes like this:
class CKey
{
public:
int key;
static const int foo = 1;
};
EOF
and I think I will use this method, but must check if it works with gcc.
thanks
when I have class consisting of 2 files:
"key.h"
class CKey
{
public:
int key;
static const int foo;
};
EOF
"key.cpp"
#include "Key.h"
const int CKey::foo = 1;
EOF
then this code doesn't work:
#include "Key.h"
int main() {
CKey obj;
int k;
switch (obj.key) {
case ( CKey::foo ): <---- error here
k = 4;
break;
}
return 0;
}
EOF
but when I write it all in one file then it works.
It works also when I initialze my static const class attributes like this:
class CKey
{
public:
int key;
static const int foo = 1;
};
EOF
and I think I will use this method, but must check if it works with gcc.
thanks
Quote:Original post by kzyczynski
It works also when I initialze my static const class attributes like this:
class CKey
{
public:
int key;
static const int foo = 1;
};
EOF
and I think I will use this method, but must check if it works with gcc.
You must have missed my last point [grin], that is only legal C++ with intergal types.
Another thing you should know there are two kinds of constants in C++ logical constant values and real constants, The above example is an example of a real constant becuase its defined in place, in the header.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement