尝试使用多态性C++时发生编译错误
compile error when trying to use polymorphism C++
我有一个基类Model,它在Model.h中声明并实现,它还包括保护:
#ifndef Model_h
#define Model_h
#include <iostream>
#include <conio.h>
#include "Node.h"
#include <map>
using namespace std;
class Node;
class Model
{
public:
void add(Node*);
protected:
map<int, Node> nodes;
};
void Model::add(Node *n)
{
nodes.insert(make_pair(n->returnTag(),*n));
}
#endif
我想要一个子类Node,它在Node.h中声明和实现,也包含保护-继承Model类,如下所示:
#ifndef Node_h
#define Node_h
#include <map>
#include <vector>
#include "Model.h"
class Node;
map<int, map<int, Node>> tnodeMap;
map<int, Node>::iterator nodeIter;
class Node:public Model
{
public:
Node();
int returnTag();
/*some code*/
};
/*implementation*/
#endif
但当我尝试构建它时,我得到了错误C2027未定义的类型"节点"如果我省略Model.h中的class Node;
语句,我会得到节点标识符的语法错误
我很困惑问题出在哪里?
您的问题与多态性无关,而是与循环依赖有关。不能在Model
中声明节点容器(如map<int, Node> nodes
),因为这会为Model
创建对Node
的依赖关系。然而,Node
依赖于Model
(因为Node
继承自Model
)。
因此出现了问题。
然而,还有其他几个问题。
- 为什么
Model
中的add方法需要一个Node指针,然后继续到一个副本(通过在地图中插入*n)?谁拥有那个指针?它的寿命是多少 - 为什么在
Node
类中全局定义了另一个Node
映射 - 为什么
Node
和Model
类在它们各自的头文件中实现?由于Model
和Node
之间存在复杂的依赖关系,如果将Node对象与标头混合,则无法实现Model取消引用Node对象。当您不使用模板时,应该将声明和实现分开 Model
和Node
之间有什么关系?你能说Node
就是Model
吗?这种等级制度在我看来很奇怪
无论如何,这里有一个固定的例子应该有效(尽管未经测试)。
型号.h
#ifndef Model_h
#define Model_h
#include <iostream>
#include <map>
#include <conio.h>
// We SHOULD NOT include Node.h in this file
class Node; // Forward declaration is enough
using namespace std;
class Model
{
public:
void add(Node*);
protected:
map<int, Node*> m_nodes;
};
#endif // Model_h
型号.cpp
#include "Model.h"
// In the implementation file we CAN NOW include Node.
#include "Node.h"
void Model::add(Node* n)
{
m_nodes.insert(make_pair(n->returnTag(), n));
}
节点.h
#ifndef Node_h
#define Node_h
#include <map>
#include <vector>
#include "Model.h"
// NO NEEED to forward declare the Node class
map<int, map<int, Node>> tnodeMap; // Why is this global?
map<int, Node>::iterator nodeIter; // Why is this global?
class Node: public Model
{
public:
Node();
int returnTag();
/*some method declarations*/
};
/* implementation IN IMPLEMENTATION FILE */
#endif // Node_h
您的两个头文件是相互依赖的。使一个头文件独立。
如果编译器试图编译第一个节点.h,它将在该文件中找到include model.h
。所以它会跳转到model.h来编译它。在这里,它找到了model.h
相关文章:
- std::is_base_of表示ctor编译错误
- Qt5:使用QCommandLineParser类时出现奇怪的编译错误
- 如何修复sfml c++代码编译错误
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 使用外部SDK工具链文件在VisualStudio上生成项目编译错误
- vscode下的Arduino代码出现意外编译错误
- 第三方 API 中的编译错误 - Visual Studio
- std::cout输出int时出现编译错误
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 提升图广度优先搜索前置编译错误
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 我在C++中遇到了这个奇怪的编译错误
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- 使用 std::enable_if 限制派生类的模板参数时出现编译错误
- 现代OpenGL和GLEW Libraray的编译错误
- C++ 编译错误:意外的类型名称"字符串":预期的表达式
- C ++程序编译错误,找不到/访问文件
- 使用直接大括号初始化时,C++ 编译错误"声明末尾的预期";"
- 为什么传递非静态成员函数会导致编译错误?