变量下面的代码全局变量修改的const成员函数,其中通过全局函数
#include <iostream>
class A
{
public:
int x;
double y;
A(int x_, double y_) : x(x_), y(y_)
{
}
void display(void) const;
};
class B
{
public:
static A staticObject;
};
void A::display(void) const
{
std::cout << x << ' ' << y << std::endl;
B::staticObject.x = 42;
B::staticObject.y = 3.5;
std::cout << x << ' ' << y << std::endl;
}
A B::staticObject(19, 29.3);
int main(void)
{
B::staticObject.display();
return 0;
}
打印出
19 29.3
42 3.5
这让我怀疑:
是否总是安全的,让一个const成员函数通过其他方式修改它被调用的对象?
此外,如果该成员函数(此处为display
)未被声明为const
,是否存在可以防止的最坏情况?
const成员函数只适用于对象的当前实例。所以当你得到同一个对象的非const实例时,你可以在那里调用非const函数。 const关键字只会使'this'->指针成为常量。 – Hayt
这种设计的背景是什么? – wasthishelpful