初始化列表:使用C 与Java中的构造函数
Initialization lists: using constructors in C++ vs Java
回答
这是我在网站上的第一篇文章。我正在尝试构建图形界面以在C 中运行一些图形算法,但是我很难获得编译代码。我从Java到C ,基本上,我想做的就是将节点(两次)传递给边缘类的构造函数。也许错误是我包括(re:title)的方式?节点和边缘是两个单独的类。这是我的错误:
Edge.cpp: In constructor ‘Edge::Edge(Node, Node, bool)’:
Edge.cpp:4: error: no matching function for call to ‘Node::Node()’
Node.h:10: note: candidates are: Node::Node(int)
Node.h:4: note: Node::Node(const Node&)
我意识到我没有定义node()构造函数,但是我试图将节点实例传递给边缘构造函数,而且我看不到添加(int)的位置。我希望我的问题足够清楚。我包括我认为相关的代码(省略node.cpp和exge.cpp的某些)。任何帮助将不胜感激。
node.h
#ifndef NODE_H
#define NODE_H
class Node {
protected:
int label;
int visited;
public:
Node(int label);
int get_label();
void visit();
bool isVisited();
void reset();
};
#endif
edge.h
#ifndef EDGE_H
#define EDGE_H
class Node;
class Edge {
protected:
Node n_one;
Node n_two;
bool directed;
public:
Edge(Node n_one, Node n_two, bool directed);
Node here();
Node there();
bool is_directed();
};
#endif
edge.cpp
#include "Node.h"
#include "Edge.h"
Edge::Edge(Node n_one, Node n_two, bool directed) { //ERROR
this->n_one = n_one;
this->n_two = n_two;
this->directed = directed;
}
....
问题是,除非另外指定,否则在构造函数启动之前将默认构建类的成员。因此,当调用您的Edge
构造函数时,它将尝试默认构造其两个Node
成员,但它们没有默认的构造函数。然后,当您进行this->n_one = n_one
时,例如,您正在尝试将复制分配给成员n_one
,而不是使用复制构造函数进行构造。
相反,如果要在构造函数中初始化成员,则应使用成员初始化列表:
Edge::Edge(Node n_one, Node n_two, bool directed)
: n_one(n_one), n_two(n_two), directed(directed)
{ }
边缘的构造函数编写不正确,因为编译器试图默认初始化数据成员node n_one;和node n_two;但是类节点没有默认构造函数。
以下方式重写类边缘的构造函数
Edge::Edge(Node n_one, Node n_two, bool directed) : n_one( n_one ), n_two( n_two ), directed( directed )
{
}
或最好将其定义为
Edge::Edge( const Node &n_one, const Node &n_two, bool directed) : n_one( n_one ), n_two( n_two ), directed( directed )
{
}
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 带有 "this" 关键字的 Java Copy 构造函数
- 在 C++ vs Java 中从构造函数调用被覆盖的方法
- Java 类型的枚举,C++中的自定义值和构造函数
- 初始化列表:使用C 与Java中的构造函数
- 默认构造函数,Java与C++
- 为什么 C++ 和 Java 中的构造函数调用需要显式类型参数
- Java是否有默认的复制构造函数(就像C++中一样)
- 在构造函数中使用重写方法的替代方法,Java
- 什么是 Java 上的隐式构造函数
- SWIG:使用%typemap(javabase)并调用java中的超类构造函数
- Java Opencv Mat构造函数不匹配
- (初学者)c++构造函数和方法的继承,使用一个Java示例作为起点