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 Game
has a member EntityManager entityManager_
.
我的班级Game
有一个成员EntityManager entityManager_
。
The class EntityManager
has 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 Player
has 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 Game
class, 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 const
from the player's getPosition function but nothing changed.
我尝试const
从播放器的 getPosition 函数中删除 ,但没有任何改变。
I know it probably has something to do with the const
but 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 getPlayer
the object/reference is const
. You cannot call a non-const member function on a const
object or through a const
reference 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
.