对象的类型限定符与成员函数不兼容。为什么会出现这个错误?

问题描述 投票:0回答:1
PVector operator + (const PVector& lhs, const PVector& rhs){
    return PVector(lhs.getX() + rhs.getX(), lhs.getY()+ rhs.getY());
}

当我使用getX()或getY()函数时,我在lhs和rhs对象上得到一个错误。该函数并没有对对象进行任何更改,它只是返回一个私有的float值。我想知道为什么会发生这种情况?我不是那么擅长用c++编程,但我想学习。

我可以从lhs和rhs对象中取出const,但我想知道为什么会出现这个错误。

谢谢你的帮助。

c++ const
1个回答
0
投票

这个编译错误表明你试图使用一个const对象的(非const)成员函数。

class A {
    void f(); 
}

const A a;
A.f(); // <- this will result in a cv qualifier compile error.

你可以通过将函数设置为const来解决这个问题。

class A {
    void f() const; 
}

这意味着,这个函数调用不会改变成员变量。因此,它可以应用在一个const对象上。

很可能你的getX和getY函数需要是const。

© www.soinside.com 2019 - 2024. All rights reserved.