0

Each of the following statements have include guards around them, for their corresponding header files.

C extends B, things subclass B so they can get a pointer to A– but A has several fields that are subclasses of B.

My current solution is to store Bs in a void array, and use template methods you return the correct object based on run-time type information. But I want to know if there is a way for A to have C fields, even if C needs to link back to A, Ahead Of Time(Compile time).

I have taken a few courses on object oriented programming(they were mostly in java), but none that focused specifically on C++.

This is probably a common problem, and this question has probably already been asked and answered here– but I don't know what keywords to use to find such a solution.

A.h

//#include "C.h" //would cause cyclical include
class A {
public:
    A();
    virtual ~A();

    /**Type must be checked at runtime, because otherwise cyclical includes occur*/
    template <class T> T* getComponent();
private:
    //C* aComponent; //desired implementation
    //Current implementation
    void* components;
    unsigned char componentCount;

};

B.h

#include "A.h"
class B {
public:
    B();
    virtual ~B();
    A* getRoot();

private:
    A* aRoot;
};

C.h

#include "B.h"
class C : B {
public:
    B();
    virtual ~B();
};

Other OOP languages I've used just resolve such problems behind the scenes, where as C++ requires that the build order be correct. I saw several answers to other questions that looked vaguely similar to this one, but they were kind of unclear, please be concise about your answer.

4

1 回答 1

1

只需使用前向声明:

class C;

将其放在顶部A.h将允许您使用类作为类型,而不是使用 void 指针。

编辑:为了澄清,这只是向编译器发出信号,表明有一些名为 的类C,但没有定义。您将能够声明指向它的指针,但在编译器看到它的实际定义之前,您将无法使用它的任何成员(这应该不是问题)。

于 2013-07-12T21:15:49.207 回答