对于一个项目,我必须编写一个容器类和元素,如果元素需要有关容器的知识--它们是in.Also --创建应该由容器中的工厂方法完成,因为如果使用头和cpp文件,这很容易,如果您(像我一样)只允许使用一个标头,这对我来说是不可能的。下面是这个问题的一个例子:
class myContainer;
class myElement;
class myContainer
{
public:
myElement *createElement()
{
myElement *me =new myElement(this);
// do some adding to list stuff
return me;
}
int askMyContainer()
{
return 42;
}
};
class myElement
{
public:
myElement(myContainer *parent)
{
pcontainer=parent;
}
int userAskingSomething()
{
return pcontainer->askMyContainer();
}
protected:
myContainer *pcontainer;
};myContainer类需要关于myElement的知识,这就是为什么myElement hat在myContainer之前,而myElement需要myContainer的知识。
发布于 2013-10-28 10:16:17
您必须将类定义和方法定义拆分为至少一个类的单独部分。
例如,首先定义myContainer类(即类及其变量/函数,而不是这些函数的实现)。然后使用myElement类。接下来是myContainer成员函数的实际实现(如果希望在头文件中标记它们,则标记为inline )。
发布于 2013-10-28 10:24:34
您可以使用其他文件拆分声明和定义,以解析圆圈:
// File myContainer.h:
#include "myElement.h"
class myContainer
{
public:
myElement *createElement();
int askMyContainer();
};
#include "myElement.hcc"
// File myContainer.hcc:
#include "myElement.h"
// inline myContainer functions
// File myElement.h
class myContainer;
class myElement
{
public:
myElement(myContainer *parent);
int userAskingSomething();
protected:
myContainer *pcontainer;
};
#include "myElement.hcc"
// File myElement.hcc
#include "myContainer.h"
// inline myElement functions发布于 2013-10-28 10:16:31
在写这个问题的时候,我有一个想法,那就是继承。喜欢
class myContainerBase
{
pulbic:
int askMyContainer()
{
return 42;
}
};
//...
class myElement
{
public:
myElement(myContainerBase *parent)
{
pcontainer=parent;
}
//...
class myContainer:public my ContainerBase
{
//...有人有更好的方法吗?或者这样行吗?
乔希姆·皮尔伯格给了我最好的答案。他的最后一句话是我以前不知道的。以下是我们其他人的工作例子:-)
class myContainer;
class myElement;
class myContainer
{
public:
myElement *createElement();
int askMyContainer()
{
return 42;
}
};
class myElement
{
public:
myElement(myContainer *parent)
{
pcontainer=parent;
}
int userAskingSomething()
{
return pcontainer->askMyContainer();
}
protected:
myContainer *pcontainer;
};
inline myElement *myContainer::createElement()
{
myElement *me =new myElement(this);
// do some adding to list stuff
return me;
}https://stackoverflow.com/questions/19632035
复制相似问题