为什么我不能在这里通过引用传递类对象?

Why I can't pass class object by reference here?

本文关键字:对象 引用 不能 在这里 为什么      更新时间:2023-10-16

我有这样一个类:

 class Token {
    std::string name; // token name
    int frequency;//frequency
    Vector lines;//lines where the token is present
public:
    //explanations for the methods in the Token.cpp
    Token(std::string tokenname, int linenumber);
    virtual ~Token();
    void newEntry(int &linenumber);
    std::string getName();
    int getFrequency();
    std::string toString();
};

还有另一个类

class Node {
    Token data;
    Node* next;
public:
    Node(const Token &v);
};

在node的构造函数中,我想传递一个常量引用到令牌对象。但是当我在cpp文件中编写方法时:

  Node::Node(const Token &v){
    data = v;
}

我得到一个编译错误:

../src/List.cpp:在构造函数' Node::Node(const Token&) '中:../src/List.cpp:11:26:错误:没有匹配函数调用' Token::Token() ' Node::Node(const Token& v){^ ../src/List.cpp:11:26:注:候选人是:In file included from ./src/List.h:10:0,from ./src/List.cpp:8: ../src/Token.h:19:2: note: Token::Token(std::string, int) Token(std::string tokenname, int linenumber);^ ../src/Token.h:19:2:注意:candidate期望2个参数,提供0 ./src/Token.h:12:7:注意:Token::Token(const Token&)类Token {^ ../src/Token.h:12:7:注意:candidate期望1个参数,提供0 make: *** [src/List]。0]错误1

我如何解决这个问题,是什么导致了这个问题?我真的想传递Token引用/

您需要像这样更改实现:

Node::Node(const Token &v) : data(v){
}

来调用正确的构造函数,否则编译器将首先调用默认构造函数(因此该消息缺少默认构造函数),然后调用赋值操作符。

根据您的代码,Token需要有一个默认的角色,但它没有。Node类中的data将首先由其默认的变量初始化,然后由operator=Node::Node的变量中赋值。您可以使用ctor初始化列表来解决,Token的复制ctor将被调用。

Node::Node(const Token &v) : data(v) {}