为什么一个const成员函数可以修改静态数据成员? [英] Why can a const member function modify a static data member?
问题描述
在下面的 C ++
程序中,修改静态数据成员从 const
函数工作正常:
class A
{
public:
static int a; //静态数据成员
void set()const
{
a = 10;
}
};
但是从<$ c $修改非静态数据成员 c> const 函数不起作用:
class A
{
public:
int a; //非静态数据成员
void set()const
{
a = 10;
}
};
为什么 const
成员函数修改一个静态
数据成员?
规则,就是这样。
$ b $
成员函数上的 const
限定符意味着您不能修改非 - mutable
非 - 静态
类成员变量。
一些合理化,在 const
限定成员函数中 this
指针是一个 const
类型,并且这个
与类的一个实例有内在联系。 static
成员与类实例无关。你不需要一个实例来修改 static
成员:你可以通过编写 A :: a = 10; 。
因此,在第一种情况下,请将 a = 10;
看作简写为 A :: a = 10;
,在第二种情况下,将其视为 this-> a = 10的简写形式; code>,由于
this
的类型是 const A *
。
In the following C++
program, modifying a static data member from a const
function is working fine:
class A
{
public:
static int a; // static data member
void set() const
{
a = 10;
}
};
But modifying a non-static data member from a const
function does not work:
class A
{
public:
int a; // non-static data member
void set() const
{
a = 10;
}
};
Why can a const
member function modify a static
data member?
It's the rule, that's all. And for good reason.
The const
qualifier on a member function means that you cannot modify non-mutable
non-static
class member variables.
By way of offering some rationalisation, the this
pointer in a const
qualified member function is a const
type, and this
is inherently related to an instance of a class. static
members are not related to a class instance. You don't need an instance to modify a static
member: you can do it, in your case, by writing A::a = 10;
.
So, in your first case, think of a = 10;
as shorthand for A::a = 10;
and in the second case, think of it as shorthand for this->a = 10;
, which is not compilable since the type of this
is const A*
.
这篇关于为什么一个const成员函数可以修改静态数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!