0

I have a set of classes to implement and I plan to do it in the following way:

(1) A master header file (entity.h) that has all the forward declarations of these classes enclosed in a namespace i.e.:

namespace SomeNameSpace {
    class A;
    ...
    class E;
}

(2) Each of the classes then have separate header files (i.e. A.h, B.h) that defines the classes and declares all the constituent variables and methods.

(3) And finally, the .cpp's that define all the members and statics (i.e. A.cpp, B.cpp).

Now, I tried to put this scheme to work by doing #include "entity.h", but I am slapped with an "ambiguity" error whenever I try to use one of these classes. If I skip step (1) and simply include all the individuals header files of each class, then I don't have that problem (and that's how I've been writing code).

So anyway, is my scheme viable? Is there some way to make it work? What I really wanted is to have some sort of way to put every custom object in one namespace. I suppose I can make that work by simply putting all the class declarations into one file, but that'd make entity.h bloated.

I've searched around with keywords "forward declaration", "C++", "namespace", "one namespace", "master header", "header" and couldn't find anything that's quite relevant. Maybe what I want to do is wrong?

4

3 回答 3

2

A different approach would be wrapping the classes into a namespace directly from the original headers, and then including them, e.g.:

A.h:

namespace SomeNameSpace {
    class A{
        // Class definition
        void something();
    }
}

A.cpp:

#include "A.h"
namespace SomeNameSpace {
    void A::something()
    {
    }
    // And other function definitions
}

entity.h:

#include "A.h"
#include "B.h"
// And so on...
于 2012-05-31T03:21:07.287 回答
2

You cannot use "class A;" in your entity.h because that means that you are actually declaring a class but you already have done so in A.h You can either add the whole declaration in your entity.h but not using any A.h, B.h etc. Or, you can just use the same namespace in each *.h file : A.h -> namespace SomeNamespace { class A ... }

B.h -> namespace SomeNamespace{ class B ... }

于 2012-05-31T03:22:33.373 回答
1

You cannot use a class in a scope where there is not a complete definition (the forward declaration is not enough). Normally you might forward declare in the header and #include in the cpp. I don't see the point in organizing the way you are trying to; The canonical wisdom is to forward declare whenever possible and #include whenever necessary.

于 2012-05-31T03:19:31.940 回答