背景:我正在研究 framework它基于现有的 Java 类模型生成 C++ 代码。因此,我无法更改下面提到的循环依赖。
给定:
- 父子类关系
- 父级包含子级列表
- 用户必须能够在运行时查找列表元素类型
我在以下测试用例中对此进行了建模:
main.cpp
#include "Parent.h"
#include <iostream>
using std::cout;
using std::endl;
int main(int argc, char* argv[])
{
Parent parent;
cout << Parent::getType() << endl;
cout << parent.getChildren().getType() << endl;
return 0;
}
父类.h
#ifndef PARENT_H
#define PARENT_H
#include <string>
#include "Array.h"
class Child;
class Parent
{
public:
Array<Child> getChildren()
{
return Array<Child>();
}
static std::string getType()
{
return "parent";
}
};
#endif
child .h
#ifndef CHILD_H
#define CHILD_H
#include "Parent.h"
class Child: public Parent
{
};
#endif
数组.h
template <typename ElementType>
class Array
{
public:
static std::string getType()
{
return ElementType::getType();
}
};
当我编译上面的代码时,我得到:
error C2027: use of undefined type 'Child'
在return ElementType::getType();
如果我尝试
#include "Child.h"
我得到的不是前向声明:error C2504: 'Parent' : base class undefined
在class Child: public Parent
如果我尝试
Array<Child*>
而不是Array<Child>
我得到:error C2825: 'ElementType': must be a class or namespace when followed by '::'
在return ElementType::getType();
循环依赖的产生是因为:
- Child.h 需要了解 Parent 类
- Parent.h 需要了解 Array 类
- Array.h 需要了解 Child 类
有什么想法吗?
最佳答案
错误是由于在实例化模板时不存在子类。
将以下内容添加到 Main 或 Parent.h 的末尾:
#include "Child.h"
这在 g++ 4 和 VS 2010 上都能很好地编译。
关于c++ - 模板、循环依赖、方法,天哪!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3177227/