class A
{
void koo(){}
void foo() const {this->koo();}
};
int main()
{
A a;
a.foo();
}
我试图在 const 函数中调用一个非常量函数。
error: passing ‘const A’ as ‘this’ argument of ‘void A::koo()’ discards qualifiers [-fpermissive]
class A
{
void koo(){}
void foo() const {this->koo();}
};
int main()
{
A a;
a.foo();
}
我试图在 const 函数中调用一个非常量函数。
error: passing ‘const A’ as ‘this’ argument of ‘void A::koo()’ discards qualifiers [-fpermissive]
在功能foo上,this有类型const A*。为了在其上调用非常量函数,您最终会this得到koo相同的值但 type A*,即它会丢弃 const 限定符。
不。
你可以,因为你碰巧知道该koo函数不会修改任何作为数据成员的 const 对象A(因为(a)函数体是空的,(b)A没有数据成员,(c)它是在非-const 实例A)。但不要那样做。
标记koo为const成员函数,同foo.
koo未声明为const,这表明它可以以某种方式更改对象,这在 const 对象上是不允许的。的签名foo表示当前对象 ( this) 应被视为常量。
您需要指定一个const变体koo:
void koo() const {}
void koo() {}
如果koo声明不是 const(即它修改了对象的内部状态),那么确实foo不是 const。
要么制作kooconst,foo而不是 const,或者如果对象表现得像“没有状态”但具有必须更新的内部变量,则制作这些变量mutable。
mutable int m_accessCount;
当您将函数声明为const时,您是在说“此函数永远不会更改对象”。这允许您在const对象上使用该功能。
在您的情况下,您正在从 const 内部调用非常量函数,这意味着您无法确保对象不会更改。这会导致错误,因为constonfoo()意味着在任何情况下都不能更改对象。
请避免使用const_cast,因为如果使用不当会导致UB。
修复它的最佳方法是提供const一个koo(). 要么编写它的非修改版本,要么(如果它不按原样修改对象)只需添加const关键字。