我遇到了一些麻烦,一个函数没有返回正确的类型,因为没有定义一个类。我使用的是工厂模式。
我得到的两个错误信息是:'return': cannot convert from 'DLA *' to 'Layer *'。
"return": 不能从 "DLA *"转换为 "Layer *
和:
"Layer":基类未定义(编译源文件src/Layer.cpp)
而这个错误信息会在每个包含有 Layer.h
.
下面是我的类,继承自 Layer
看起来像(DLA.h
):
#pragma once
#ifndef _DLA
#define _DLA
#include "ofMain.h"
#include "ofxGui.h"
#include "Layer.h"
class DLA: public Layer
{
public:
DLA();
void setup();
void update();
void draw();
private:
};
#endif
这是我的 Layer
类头 (Layer.h
):
#pragma once
#ifndef _LAYER
#define _LAYER
#include "ofMain.h"
#include "ofxGui.h"
#include "DLA.h"
enum SceneType
{
Scene_None,
Scene_Default,
Scene_DLA,
};
class Layer
{
public:
void setup();
void update();
void draw();
static Layer *CreateSimulation(SceneType Type);
private:
};
#endif
失效的功能是这个功能,位于... Layer.cpp
:
Layer *Layer::CreateSimulation(SceneType Type)
{
switch (Type)
{
case Scene_None:
default:
return nullptr;
case Scene_DLA:
return new DLA();
}
}
我已经尝试了Stack Overflow上所有能找到的和我类似的问题,但是我看到有些人推荐了非常细微的代码缩进来解决这个问题,所以我真的不知道问题出在哪里。
就目前而言,你的头文件引起了 循环依赖性虽说 #pragma once
(和其他)防护措施防止任何实际的 "无限递归"。让我们从编译器的角度来看一下,在编译 Layer.cpp
文件(或任何其他'.cpp'源码,其中有 #include "Layer.h"
中)。)
编译器遇到 #include "Layer.h"
(这是它第一次这样做--警卫不会被 "触发"),所以它适时地用指定的头的内容替换了这一行。在这些内容中,它遇到了 #include "DLA.h"
我们可以忽略本次讨论中包含的其他标题,假设它们与当前的问题无关)。所以,它就适当地替换了 该 的内容的一行。DLA.h
头,这时它将会遇到这个。
#include "Layer.h"
class DLA: public Layer
{
现在,在这里,当它替换掉 #include "Layer.h"
的头内容,该内容将是 "空的"(因为有了防护罩,因为它已经包含了该头内容)。曾经). 因此,当 public Layer
遇到代码,这是一个错误,因为该类还没 还 被定义,甚至被声明为一个类。
所以,如果你 硬要 在拥有 #include "DLA.h"
一行 Layer.h
那么,它 必须 处于 之后 的定义 Layer
类。
然而,一个更好的方法是去掉 #include "DLA.h"
从 Layer.h
,并且只把它放在 源头 (.cpp)文件,真正需要它的文件(如 Layer.cpp
). 这将是很好的工作。
// Layer.cpp
#include "Layer.h"
#include "DLA.h" // At this point, references to the Layer class in DLA.h will be fine!
//...
Layer *Layer::CreateSimulation(SceneType Type)
{
switch (Type)
{
case Scene_None:
default:
return nullptr;
case Scene_DLA:
return new DLA();
}
}
随时随地作为K任何进一步的澄清或解释。