【问题标题】:Object has type qualifiers that are not compatible with the member function对象具有与成员函数不兼容的类型限定符
【发布时间】:2014-08-31 20:34:31
【问题描述】:

我的班级Game 有一个成员EntityManager entityManager_

EntityManager 类有一个私有成员 Player player_ 和一个返回 player_ 的公共 getter 函数 Player &EntityManager::getPlayer()

Player 类具有例如函数void startMoving()sf::Vector2f getPosition() const

现在,我可以毫无问题地从我的 Game 类中调用 entityManager_.getPlayer().startMoving();,但是当我尝试使用以下代码获取玩家的位置时:

sf::Vector2f playerPosition = entityManager_.getPlayer().getPosition();

我收到以下错误:

智能感知:

EntityManager Game::entityManager_

Error: the object has type qualifiers that are not compatible with the member function

object type is: const EntityManager

输出:

game.cpp(261): error C2662: 'EntityManager::getPlayer' : cannot convert 'this' pointer from 'const EntityManager' to 'EntityManager &'
          Conversion loses qualifiers

我尝试从播放器的 getPosition 函数中删除 const,但没有任何改变。

我知道这可能与const 有关,但我不知道要更改什么!有人可以帮我吗?

【问题讨论】:

  • 我怀疑你没有 const 版本的 getPlayer 但你没有显示任何代码。
  • const 添加到getPlayer 可以消除错误,但是你能告诉我我必须返回什么而不是player_ 吗?因为现在getPlayer 告诉我:error: qualifiers drop in reference of type "Player &" to initializer of type "const Player"
  • @A.D.:你是否在一个本身声明为const的成员函数中?
  • @DavidRodríguez-dribeas 啊,是的。该成员函数确实是const。我删除了它,现在它可以工作了!谢谢
  • 你需要Player &EntityManager::getPlayer() { return _player; }const Player &EntityManager::getPlayer() const { return _player; }

标签: c++ types constants compatibility qualifiers


【解决方案1】:

错误信息非常明确:

game.cpp(261): error C2662: 'EntityManager::getPlayer' : 
               cannot convert 'this' pointer from 'const EntityManager' to 
                                                  'EntityManager &'
          Conversion loses qualifiers

在您调用getPlayer 的上下文中,对象/引用是const。您不能在 const 对象上或通过 const 引用或指向 const 的指针调用非常量成员函数。

因为错误指向this,最可能的原因是这段代码在const的成员函数内。

【讨论】:

    猜你喜欢
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多