如何从同一个头文件中定义 2 个 class,而一个 class 依赖于另一个?
How can I define 2 classes from the same header file, while one class depends on the other?
我目前正在尝试实现一个简单的寻路算法并且需要它的边和节点。我想在一个 .h 和一个 .cpp 文件中处理这些实现。现在我收到错误 "expected constructor, destructor or type conversion before ..."。
我已经尝试将 类 分成 2 个 .h 和 .cpp 文件,但这也没有用。我已经尝试了很多为该错误消息提供的解决方案,但似乎没有任何效果,我认为我现在缺少一些东西。
我的 utilites.cpp 文件看起来有点像那样
#include "utilities.h"
//Class Node
//Public
using namespace std;
Node::Node(string name)
{
this->name = name;
}
//Class Edge
//public
Edge::Edge(Node::Node nSource, Node::Node nTarget, int weight)
{
this->nSource = nSource;
this->nTarget = nTarget;
this->weight = weight;
}
和我的 utilities.h:
#ifndef UTILITIES_H
#define UTILITIES_H
#include <string>
#include <list>
class Node
{
public:
Node(std::string);
std::string name;
};
class Edge
{
public:
Edge(Node, Node, int);
Node nSource;
Node nTarget;
int weight;
};
#endif /* end of include guard: UTILITIES_H */
如果我只使用 Class 节点,一切正常。
但是如果我想用 Class 节点实现 Class Edge,我会得到前面提到的错误。我认为这很容易解决,但我就是想不通。
我应该说我已经用
试过了
Edge::Edge(Node nSource, Node nTarget, int weight)
{
this->nSource = nSource;
this->nTarget = nTarget;
this->weight = weight;
}
但这只是给了我错误“没有匹配函数来调用 'Node::Node()'
问题是我在 Node
的默认构造函数之后缺少花括号
Node(){};
现在它按预期工作了。
感谢您的回答,他们让我再次仔细研究了默认构造函数...
我目前正在尝试实现一个简单的寻路算法并且需要它的边和节点。我想在一个 .h 和一个 .cpp 文件中处理这些实现。现在我收到错误 "expected constructor, destructor or type conversion before ..."。
我已经尝试将 类 分成 2 个 .h 和 .cpp 文件,但这也没有用。我已经尝试了很多为该错误消息提供的解决方案,但似乎没有任何效果,我认为我现在缺少一些东西。
我的 utilites.cpp 文件看起来有点像那样
#include "utilities.h"
//Class Node
//Public
using namespace std;
Node::Node(string name)
{
this->name = name;
}
//Class Edge
//public
Edge::Edge(Node::Node nSource, Node::Node nTarget, int weight)
{
this->nSource = nSource;
this->nTarget = nTarget;
this->weight = weight;
}
和我的 utilities.h:
#ifndef UTILITIES_H
#define UTILITIES_H
#include <string>
#include <list>
class Node
{
public:
Node(std::string);
std::string name;
};
class Edge
{
public:
Edge(Node, Node, int);
Node nSource;
Node nTarget;
int weight;
};
#endif /* end of include guard: UTILITIES_H */
如果我只使用 Class 节点,一切正常。 但是如果我想用 Class 节点实现 Class Edge,我会得到前面提到的错误。我认为这很容易解决,但我就是想不通。
我应该说我已经用
试过了Edge::Edge(Node nSource, Node nTarget, int weight)
{
this->nSource = nSource;
this->nTarget = nTarget;
this->weight = weight;
}
但这只是给了我错误“没有匹配函数来调用 'Node::Node()'
问题是我在 Node
的默认构造函数之后缺少花括号Node(){};
现在它按预期工作了。 感谢您的回答,他们让我再次仔细研究了默认构造函数...