C++ 对象具有与成员函数不兼容的类型限定符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24677032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Object has type qualifiers that are not compatible with the member function
提问by A. D.
My class Gamehas a member EntityManager entityManager_.
我的班级Game有一个成员EntityManager entityManager_。
The class EntityManagerhas a private member Player player_and the public getter function Player &EntityManager::getPlayer()which returns player_.
该类EntityManager有一个私有成员Player player_和Player &EntityManager::getPlayer()返回player_.
The class Playerhas for example the functions void startMoving()and sf::Vector2f getPosition() const.
Player例如,该类具有函数void startMoving()和sf::Vector2f getPosition() const.
Now, I can without problems call entityManager_.getPlayer().startMoving();from within my Gameclass, but when I try for example the following code to get the player's position:
现在,我可以毫无问题地entityManager_.getPlayer().startMoving();从我的Game班级中调用,但是当我尝试使用以下代码来获取玩家的位置时:
sf::Vector2f playerPosition = entityManager_.getPlayer().getPosition();
sf::Vector2f playerPosition = entityManager_.getPlayer().getPosition();
I get the following error:
我收到以下错误:
IntelliSense:
智能感知:
EntityManager Game::entityManager_
Error: the object has type qualifiers that are not compatible with the member function
object type is: const EntityManager
Output:
输出:
game.cpp(261): error C2662: 'EntityManager::getPlayer' : cannot convert 'this' pointer from 'const EntityManager' to 'EntityManager &'
Conversion loses qualifiers
I tried removing the constfrom the player's getPosition function but nothing changed.
我尝试const从播放器的 getPosition 函数中删除 ,但没有任何改变。
I know it probably has something to do with the constbut I can't figure out what to change! Could someone please help me?
我知道这可能与 ,const但我不知道要改变什么!有人可以帮我吗?
回答by David Rodríguez - dribeas
The error message is quite explicit:
错误信息非常明确:
game.cpp(261): error C2662: 'EntityManager::getPlayer' :
cannot convert 'this' pointer from 'const EntityManager' to
'EntityManager &'
Conversion loses qualifiers
In the context where you are calling getPlayerthe object/reference is const. You cannot call a non-const member function on a constobject or through a constreference or pointer to const.
在您调用getPlayer对象/引用的上下文中是const. 您不能在const对象上调用非常量成员函数,也不能通过对 的const引用或指针调用const。
Because the error refers to this, the most likely reason is that this code is inside a member function that is const.
因为错误指的是this,最可能的原因是此代码位于const.

