可能重复:
Invoking a nonconst method on a member from a const method为什么const成员函数能够通过成员指针调用非const成员函数?
常量成员函数可以调用通过指针成员变量的非恒定成员函数在C++中,它是如预期? 下面给出的代码片段正在编译
#include <iostream>
class S {
public:
void hi() {
std::cout << "Hi" << std::endl;
}
};
class T {
public:
T()
: s(new S())
{}
~T()
{
delete s;
}
void hi() const {
s->hi();
}
private:
S * s;
};
int main(int argc, char ** argv) {
T t;
t.hi();
return 0;
}
我们还没有在类中声明S * const s,那么它如何可以是一个常量指针呢? – Kenta