On 15 Apr., 20:27, slatp <songli9...@[EMAIL PROTECTED]
> wrote:
> //1.h
> class A
> {
> public:
> enum B{a,b,c};
>
> };
>
> //2.h
>
> how to declare enum B?
> class C
> {
> public:
> void func(A::B m);
>
> };
There are two problems with this code:
1) You cannot declare a *member* of a class, if the
definition of this class is not yet available.
2) Classic enumerations do not allow any forward declaration.
The reason for the second constraint is, that the compiler
cannot know at the point of a non-defining declaration
which size the enum will have. This is relevant, because
the standard allows that the compiler might take advantage
to use the most compressed form that is possible given
an existing enum definition. If it would be allowed to
forward-declare enums then you could declare a function
like this:
enum E; // Forbidden, but let's dream for a while..
void foo(E*); // [1]
The declaration [1] causes a problem, because compilers
can use a pointer type representation depending on the
the actual underlying-type of the enum, *if this enumeration
definition is visible* at this point, but alas - this is
not the case here.
But - "hope is the last to die" - due to a fruitful discussion
which began in comp.std.c++ with Alberto Barbati's thread
http://preview.tinyurl.com/4msy54
a nice extension proposal was submitted:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2568.pdf
The short answer is, that this proposal makes an enumeration
declaration well-formed, provided it belongs to the new
enumeration declaration style that allows to provide the
underlying type of the enum. In this case your example
could use the following form:
//1.h
enum E : int {a,b,c}; // Provide the definition for E with
// underlying type int. Use another type, if you prefer.
class A
{
public:
typedef E B; // Synchronize E with B
};
//2.h
// Declare enum E (A ensures that A::B is equivalent to E):
enum E : int;
class C
{
public:
void func(E m);
};
E is declared and defined outside of class B, which
is the only feasible workaround to solve problem (1).
Problem (2) is solved by using an enum type with
provided underlying type.
Of course this wont work with today's compilers.
I recommend in this case the introduction of a
separate header, which defines the enum, this header
is than included in both A and C:
//e.h
enum E {a,b,c}; // Provide the definition for E
//1.h
#include "e.h"
class A
{
public:
typedef E B; // Synchronize E with B
};
//2.h
#include "e.h"
class C
{
public:
void func(E m);
};
HTH & Greetings from Bremen,
Daniel Krügler
--
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


|