对象具有与成员函数不兼容的类型限定符

Object has type qualifiers that are not compatible with the member function

本文关键字:类型 不兼容 函数 成员 对象      更新时间:2023-10-16

我的类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有关,但我不知道该改变什么!有人能帮帮我吗?

错误信息相当明确:

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

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

由于错误指向this,因此最有可能的原因是该代码位于const成员函数内部。