【问题标题】:Why is my compiler throwing a "Conversion loses (const) qualifiers" error when I call a const getter function?当我调用 const getter 函数时,为什么我的编译器会抛出“Conversion lost (const) qualifiers”错误?
【发布时间】:2020-04-12 14:48:50
【问题描述】:

我正在编写经典火炮游戏 Scorched Earth 的克隆(好像这些游戏还不够),但遇到了一个让我困惑的问题。我的 Player 类中有一个 getter 函数,它返回玩家名称的 const 副本。

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 引用以避免复制。

【问题讨论】:

    标签: c++ qt class constants


    【解决方案1】:
    const std::string Player::getName()
    

    const 这里没有任何作用。您正在返回一个值——m_name 的值。 值不能是const,因为更改值总是会产生不同的值。

    你想要的是一个const 函数,它允许调用const-qualified 成员。您将它们定义如下:

    std::string Player::getName() const
    

    此外,让这样的 getter 返回 const std::string& 以避免不必要的复制是很常见的。当然,const-qualify 引用返回的东西确实有意义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-16
      • 1970-01-01
      • 2023-02-01
      • 2017-01-19
      相关资源
      最近更新 更多