簡體   English   中英

當我調用 const getter 函數時,為什么我的編譯器會拋出“轉換丟失(const)限定符”錯誤?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM