【问题标题】:error C2504 circular inclusion错误 C2504 循环包含
【发布时间】:2014-04-21 18:08:28
【问题描述】:

我有父类和子类。子继承自父。我想将父对象的子对象存储在子对象的向量中。

我将 Child 标头包含在 Parent 标头中,但我必须将 Parent 标头包含在 Child 标头中(因为它继承自 Parent)。

如何克服这种循环包含?

Parent.h

#pragma once
#include <vector>
#include "Child.h"

using std::vector;
class Parent
{
public:
    Parent();
    ~Parent();
    vector<Child> children;
};

Parent.cpp

#include "stdafx.h"
#include "Parent.h"


Parent::Parent()
{   
}


Parent::~Parent()
{
}

Child.h

#pragma once
#include "Parent.h"
class Child : Parent
{
public:
    Child();
    ~Child();
};

Child.cpp

#include "stdafx.h"
#include "Child.h"


Child::Child()
{
}


Child::~Child()
{
}

错误

child.h(4): 错误 C2504: 'Parent' : 基类未定义

parent.h(11): error C2065: 'Child' : undeclared identifier

【问题讨论】:

  • 不要将基本类型存储在容器中,您需要存储指针/引用来代替运行时多态性。

标签: c++ inheritance include


【解决方案1】:

转发声明Child,并将指针存储在vector内。

Parent.h

#pragma once
#include <vector>

using std::vector;
class Child;
class Parent
{
public:
    Parent();
    ~Parent();
    vector<Child*> children;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-14
    • 2014-09-03
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 2013-09-19
    • 2017-11-07
    相关资源
    最近更新 更多