Я знаю, что об этом много спрашивали, но единственные ответы, которые я мог найти, это когда константа была фактически отброшена с помощью (int *) или аналогичного . Почему нет t квалификатор 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 for brevity)
};
int main(void)
{
const foo foobar; // NOTE: foobar is const
foobar.doit();
}
Приведенный выше код дает следующий результат (протестирован в gcc 4.5.2 и vc100):
foo::doit() const calling mybar1->doit() bar::doit() non-const <-- Why ? calling mybar2.doit() bar::doit() const