Thank you kindly for your quick and helpful response, and extra comments.
On Mon, 16 Apr 2007 00:29:50 +0100, "MRe" <m.r.e.@.d.u.b.l.i.n...i.e>
wrote:
Hi,
Sorry if this is a stupid question; but I cannot find/workout an
answer..
I have a struct that contains a constant..
// item.h
#pragma once
struct item
{ static int const item_type_a;
static int const item_type_b;
int ItemType;
};
..And I want to use it in a switch statement in a different file..
// main.cpp
#include "item.h"
void foo(item* pItem)
{ switch(pItem->ItemType;
{ case item::item_type_a: /* .. */ break;
case item::item_type_b: /* .. */ break;
}
..But am having the following problems,
If I initialise the constant values in another file..
// item.cpp
#include "item.h"
int const item::item_type_a = 0;
int const item::item_type_b = 1;
..I get the error [case expression not constant] (on the switch's case
statement)
Right, you need to initialize the constants when you declare them in the
header file.
If I initialise the constant in item.h..
// item.h
struct item
{ static int const item_type_a = 0;
..
..The error is [pure specifier can only be specified for functions]
That's what you need to do. Sounds like you're using VC6, which didn't
support this C++ feature.
or in a different playce in item.h..
struct
{ .. };
int const item::item_type_a = 0;
..
..The error is [<type> already defined ..] (I thought '#pragma once'
was
suppose to stop this?)
If more than one file #includes the header, you'll violate the
one-definition rule, so it isn't going to help.
Finally, the only way I can get it to work is if I initialise them in
main.cpp..
// main.cpp
#include "item.h"
int const item::type_line = 0;
int const item::type_circle = 1;
void foo(item* pItem)
{ switch(pItem->ItemType;
..
..So this works, but I don't like that item.h or item.cpp isn't
responsible for setting up its values (plus I can't use it in other files)
Hoping someone can tell me how I can fix this, I'm using MSVC6.
Your best bet it to move the constants out of the class and make them
global or namespace-scope constants. VC6 is nearly 10 years old and way
out
of date. Consider upgrading or at least trying the free Express editions,
which are cut down but may suit your needs.
--
Doug Harrison
Visual C++ MVP