扩展类c ++的循环包含问题

时间:2015-04-05 19:28:18

标签: c++ polymorphism

你能弄清楚如何解决这个循环包含问题吗?

C延伸B,B包括A. A包括C.我尝试的每个前瞻声明都没有用。

错误

错误1错误C2504:'B':基类未定义 错误2错误C3668:'C :: c':具有覆盖说明符'override'的方法未覆盖任何基类方法

档案A.h:

#pragma once

#include "C.h"

struct A
{
    A();

    C c;
};

档案B.h:

#pragma once

#include "A.h"

struct A;

struct B
{
    virtual void c() = 0;

    A* a;
};

档案C.h:

#pragma once

#include "B.h"

struct B;

struct C : public B
{
    void c() override;
};

1 个答案:

答案 0 :(得分:1)

解决方案总是一样的,看起来你走在了正确的轨道上。但是,您没有正确使用前向声明。应该有许多示例,例如here

B.h

// Why are including "A.h" here, this is causing your circular include
// issue, it needs to be moved to your implementation (e.g., "B.cpp")
#include "A.h"

struct A; // Forward declaration, good

struct B
{
    virtual void c() = 0;

    A* a; // A pointer only requires the above forward declartion
};

C.h

#include "B.h" // Necessary since you're extending `B`

struct B; // This forward declaration is superfluous and should be removed

struct C : public B
{
    void c() override;
};