为什么我不能在这里通过引用传递类对象?
Why I can't pass class object by reference here?
我有这样一个类:
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) {}
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 我们可以有一个 setter 成员函数作为从 const 对象引用的 const 吗?
- C++对象引用返回不同的值
- 对象引用中的字段以不同的方法返回不同的值
- 通过向构造函数其他对象引用页面来创建对象
- 为什么在对象引用恒定时允许更改为另一个类的指针的成员变量
- 如何在C++中读取 HDF5 对象引用
- C++ 未定义的对象引用
- 从函数返回 libconfig 类设置对象引用
- qt vsaddin错误对象引用未设置为对象的istanse
- 在这种情况下,为什么使用 *此必需的对象引用返回对象引用
- 基本C - 构造contaning对象引用,并将其作为方法参数传递
- C :将对象引用作为参数给出错误:呼叫class :: function()的匹配函数
- C++OOP基础知识-是否正确返回对象引用
- 使用对象引用(可能)在调用destructor后使用对象引用
- 创建返回对象引用的成员函数的最简单方法
- 如何在C++上使用对象引用删除对象
- JNI/Android NDK-维护全局对象引用
- 为什么有些类方法返回"*this"(self的对象引用)?
- 在C++中返回伪对象引用的规则