我知道这已被问过很多,但我能找到的唯一答案就是当const-ness实际上是使用(int*)或类似的方法进行的.当没有涉及强制转换时,为什么const限定符不在const对象上处理指针类型成员变量?
#include <iostream>
class bar {
public:
void doit() { std::cout << " bar::doit() non-const\n"; }
void doit() const { std::cout << " bar::doit() const\n"; }
};
class foo {
bar* mybar1;
bar mybar2;
public:
foo() : mybar1(new bar) {}
void doit() const {
std::cout << "foo::doit() const\n";
std::cout << " calling mybar1->doit()\n";
mybar1->doit(); // This calls bar::doit() instead of bar::doit() const
std::cout << " calling mybar2.doit()\n";
mybar2.doit(); // This calls bar::doit() const correctly
}
// ... (proper copying elided …Run Code Online (Sandbox Code Playgroud)