[我正在写经典火炮游戏《焦土》的克隆版(好像还不够),遇到了令我困惑的问题。我的Player类中有一个getter函数,该函数返回播放器名称的const副本。
const std::string Player::getName()
{
return this->m_name;
}
我正在使用吸气剂在我的视口上设置文本标签的文本,以反映当前轮到的玩家的姓名。
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 std::string Player::getName()
这不是const
函数,因此不允许在const
限定成员上调用它。您想要:
const std::string Player::getName() const
而且,这样的getter返回const std::string&
以避免不必要的复制是很常见的。