C++ 对象具有与成员函数不兼容的类型限定符
我的类C++ 对象具有与成员函数不兼容的类型限定符,c++,types,constants,compatibility,qualifiers,C++,Types,Constants,Compatibility,Qualifiers,我的类Game有一个成员EntityManager EntityManager\uu 类EntityManager有一个私有成员Player-Player和公共getter函数Player&EntityManager::getPlayer(),该函数返回Player 例如,类Player具有函数void startMoving()和sf::Vector2f getPosition()const 现在,我可以毫无问题地调用entityManager_uz.getPlayer().startMovi
Game
有一个成员EntityManager EntityManager\uu
类EntityManager
有一个私有成员Player-Player
和公共getter函数Player&EntityManager::getPlayer()
,该函数返回Player
例如,类Player
具有函数void startMoving()
和sf::Vector2f getPosition()const
现在,我可以毫无问题地调用entityManager_uz.getPlayer().startMoving()代码>在我的游戏
类中,但当我尝试以下代码以获取玩家的位置时:
sf::Vector2f playerPosition=entityManager_zy.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函数中删除常量,但没有任何改变
我知道这可能与常量有关,但我不知道该更改什么!有人能帮我吗?错误信息非常明确:
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
成员函数中,我怀疑您没有getPlayer的const版本,但您没有显示任何代码。将const
添加到getPlayer
会删除错误,但是你能告诉我我必须返回什么而不是player\uuuu
?因为现在getPlayer
告诉我:错误:将类型“Player&”的引用中的限定符丢弃到类型“constplayer”@A.D.的初始值设定项中:您是否在声明为const
的成员函数中?@DavidRodríguez dribeas啊,是的。该成员函数实际上是const
。我把它取下来了,现在它开始工作了!谢谢你需要Player&EntityManager::getPlayer(){return\u Player;}
和const Player&EntityManager::getPlayer()const{return\u Player;}