【发布时间】: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