c++:丢弃限定符,即使成员变量是可变的
c++ : discards qualifier even if the member variables are mutable
我在使用 const/mutable 时遇到一些问题并受到保护。也许这些让我有点困惑,所以我举个例子。
class Base
{
virtual void foo() const ;
protected :
void bar( int y ){ d_x = y } ;
private :
mutable int d_x ;
}
因此基础 class 具有虚拟 foo
。
class Derived : public Base
{
void foo() const { bar(5); }
private :
mutable int d_x ;
}
所以在我派生的 class 中我实现了 foo
,其中 class bar
然后写入私有 d_x.
我认为没问题 - 但编译器说:
passing 'Derived' as 'this' argument of bar discards qualifier.
这是为什么?我想通过使用 mutable 我可以使我的成员函数成为常量。
Const 成员函数 foo
调用非常量成员函数 bar
。调用 bar
需要非常量 this
,而 this
是指向 foo
.
内部的 const
的指针
要么 bar
必须是常量,要么 foo
必须是非常量。
从 const 限定函数(例如 foo
)内部,您只能调用其他 const 限定函数。 bar
不是 const 限定函数。
bar
仅触及 d_x
这一事实无关紧要。 d_x
的可变性仅仅意味着一个const限定的成员函数可以直接修改它。正式地,bar
可以修改 任何 成员(如果它们存在的话)。
我在使用 const/mutable 时遇到一些问题并受到保护。也许这些让我有点困惑,所以我举个例子。
class Base
{
virtual void foo() const ;
protected :
void bar( int y ){ d_x = y } ;
private :
mutable int d_x ;
}
因此基础 class 具有虚拟 foo
。
class Derived : public Base
{
void foo() const { bar(5); }
private :
mutable int d_x ;
}
所以在我派生的 class 中我实现了 foo
,其中 class bar
然后写入私有 d_x.
我认为没问题 - 但编译器说:
passing 'Derived' as 'this' argument of bar discards qualifier.
这是为什么?我想通过使用 mutable 我可以使我的成员函数成为常量。
Const 成员函数 foo
调用非常量成员函数 bar
。调用 bar
需要非常量 this
,而 this
是指向 foo
.
const
的指针
要么 bar
必须是常量,要么 foo
必须是非常量。
从 const 限定函数(例如 foo
)内部,您只能调用其他 const 限定函数。 bar
不是 const 限定函数。
bar
仅触及 d_x
这一事实无关紧要。 d_x
的可变性仅仅意味着一个const限定的成员函数可以直接修改它。正式地,bar
可以修改 任何 成员(如果它们存在的话)。