初始化列表:使用C 与Java中的构造函数

Initialization lists: using constructors in C++ vs Java

本文关键字:Java 构造函数 列表 使用 初始化      更新时间:2023-10-16

回答

这是我在网站上的第一篇文章。我正在尝试构建图形界面以在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 ) 
{
}