相关疑难解决方法(0)

为什么const限定符不能处理const对象上的指针成员?

我知道这已被问过很多,但我能找到的唯一答案就是当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)

c++ pointers const data-members

7
推荐指数
1
解决办法
363
查看次数

标签 统计

c++ ×1

const ×1

data-members ×1

pointers ×1