문제

I have chained methods like that:

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

The 2nd method is passing commandName which is wrong type as the 1st method needs reference, not an object. Then I've tried this:

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

as stated here: How to cast/convert pointer to reference in C++ - because &commandName gives me pointer... but it's passing an object again. What am I doing the silly way? As probably it's something trivial...

도움이 되었습니까?

해결책

There is nothing wrong with the original code. A reference can bind to an object.

(And in fact, no expression ever has a reference type. Expressions can be lvalues, xvalues, or prvalues, and commandName here is an lvalue, so an lvalue reference can bind to it.)

다른 팁

Your code has no problem. But you should instead pass the const reference, Since you are not really modifying the value of 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));
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top