背景:我正在致力于生成基于现有Java类模型的C++代码的framework。出于这个原因,我不能改变下面提到的循环依赖。模板,循环依赖,方法,哦,我的!
考虑:
- 父子类关系
- 家长包含儿童的名单
- 用户必须能够查找列表元素类型在运行时
我已经在下面的测试用例中对此进行了建模:
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;
}
Parent.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
Array.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.h需要了解类Array
- Array.h需要了解类儿童
任何想法?
它知道它的派生类的家长对我来说似乎是一个设计缺陷。 – Shirik 2010-07-05 04:36:47
够公平的,但正如我所解释的,我无能为力去改变这一点。我正在生成基于野外设计的代码。 – Gili 2010-07-05 04:42:05
代码'ElementType child;'在哪里? – rlbond 2010-07-05 04:49:33