传递参数的参考(本身就是参考)目标

时间:2014-04-06 18:16:01

标签: c++ pointers reference pass-by-reference

我有这样的方法:

PureCommand Hasher::nameToPure(CommandName& commandName) {
    return this->commandHash.find(commandName).value();
}
ByteCommand Hasher::nameToByte(CommandName& commandName) {
    return this->pureToByte(this->nameToPure(commandName));
}

第二种方法是传递commandName,它是错误的类型,因为第一种方法需要引用,而不是对象。然后我试过这个:

ByteCommand Hasher::nameToByte(CommandName& commandName) {
    return this->pureToByte(this->nameToPure(*&commandName));
}

如下所述:How to cast/convert pointer to reference in C++ - 因为& commandName给了我指针......但是它又传递了一个对象。我在做什么愚蠢的方式?可能它是微不足道的......

2 个答案:

答案 0 :(得分:2)

原始代码没有任何问题。引用可以绑定到对象。

(事实上,没有表达式有引用类型。表达式可以是左值,x值或prvalues,commandName这里是左值,因此左值引用可以绑定它。)

答案 1 :(得分:2)

您的代码没有问题。但是你应该传递const引用,因为你并没有真正修改commandName的值。

 PureCommand Hasher::nameToPure(const CommandName& commandName) {
    return this->commandHash.find(commandName).value();
}
ByteCommand Hasher::nameToByte(const CommandName& commandName) {
    return this->pureToByte(this->nameToPure(commandName));
}