C++ 常量不匹配:2 个重载没有对“this”指针的合法转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6639264/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:27:44  来源:igfitidea点击:

Const mismatches: 2 overloads have no legal conversion for 'this' pointer

c++vectorconstthis-pointer

提问by Griffin

I'm getting this weird error:

我收到这个奇怪的错误:

error C2663: 'sf::Drawable::SetPosition' : 2 overloads have no legal conversion for 'this' pointer

错误 C2663:“sf::Drawable::SetPosition”:2 个重载没有“this”指针的合法转换

I think it has something to do with const mismatches but I don't know where, or why. In the following code I have a vector of shapes and sprites, and when trying to access one of the vectors shapes and calling one of its functions I'm getting the error.

我认为这与 const 不匹配有关,但我不知道在哪里,也不知道为什么。在下面的代码中,我有一个形状和精灵的向量,当尝试访问其中一个向量形状并调用它的一个函数时,我收到了错误。

std::vector<sf::Shape> Shapes;
std::vector<sf::Sprite> Sprites;

bool AddShape(sf::Shape& S){
    Shapes.push_back(S); return true;
};
bool AddSprite(sf::Sprite& S){
    Sprites.push_back(S); return true;
};

private:

virtual void Render(sf::RenderTarget& target) const {                
    for(unsigned short I; I<Shapes.size(); I++){
        Shapes[I].SetPosition(
            Shapes[I].GetPosition().x + GetPosition().x,
            Shapes[I].GetPosition().y + GetPosition().y);
        target.Draw(Shapes[I]);
    }
    for(unsigned short I; I<Sprites.size(); I++){
        target.Draw(Sprites[I]);
    }
}

How can I fix this?

我怎样才能解决这个问题?

回答by eran

Renderis declared with a constafter the parameters. This means it does not change its object. Which means, that all of the object's member variables are considered constants within Render, as changing their state means changing the containing object. Assuming Shapesis a member variable, and that SetPositiondoes change the shape (i.e. not declared as const), you cannot call it within a constmember function.

Renderconst在参数后用 a 声明。这意味着它不会改变它的对象。这意味着,对象的所有成员变量都被视为 内的常量Render,因为更改它们的状态意味着更改包含对象。假设Shapes是一个成员变量,并且SetPosition确实改变了形状(即未声明为const),则不能在const成员函数中调用它。

So, remove the constfrom Renderand you'll be fine (you fix your logic, in case it must be const).

所以,删除constfrom Render,你会没事的(你修复你的逻辑,以防它必须是常量)。