[英]Why is my compiler throwing a "Conversion loses (const) qualifiers" error when I call a const getter function?
我正在編寫經典火炮游戲 Scorched Earth 的克隆(好像這些游戲還不夠),並且遇到了一個讓我感到困惑的問題。 我的 Player 類中有一個 getter 函數,它返回玩家姓名的常量副本。
const std::string Player::getName()
{
return this->m_name;
}
我正在使用 getter 在我的視口上設置文本標簽的文本,以反映當前輪到它的玩家的姓名。
void Tanx::handlePlayerEvents(const Player& player)
{
QObject::connect(&player, &Player::aimChanged, this, [=](int angle) {this->angleSlider->setValue(angle); });
this->playerNameDisplay->setText((QString::fromStdString(player.getName())));
}
我的編譯器拋出這些錯誤,即使我的返回值是 const,並且 QString::fromStdString 接受對 std::string 的 const 引用。
1>C:\Users\Dominic\source\repos\Tanx\tanx.cpp(85,74): error C2662: 'const std::string Player::getName(void)': cannot convert 'this' pointer from 'const Player' to 'Player &'
1>C:\Users\Dominic\source\repos\Tanx\tanx.cpp(85,59): message : Conversion loses qualifiers
1>C:\Users\Dominic\source\repos\Tanx\Player.h(63,20): message : see declaration of 'Player::getName' (compiling source file tanx.cpp)
我很難弄清楚問題是什么,我認為對於具有實際編碼技能的人來說,這可能會令人尷尬地清楚。 感謝您的幫助!
[編輯] 感謝大衛施瓦茨! 聲明函數,而不僅僅是作為 const 的返回值工作得很好。 此外,返回一個 const 引用以避免復制的好建議。
const std::string Player::getName()
這里的const
不做任何事情。 您正在返回一個值—— m_name
的值。 值不能是const
因為更改值總是會產生不同的值。
你想要的是一個const
函數,一個允許調用const
限定成員的const
。 您可以按如下方式定義它們:
std::string Player::getName() const
此外,像這樣的 getter 返回一個const std::string&
以避免不必要的副本是很常見的。 當然, const
限定引用返回的內容確實有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.