const 方法可以改变(智能)指针成员指向的对象

《C++ Primer 5th》 P406

const 方法,不能修改指针本身,但是可以修改指针指向的对象!

class Foo {
   public:
    Foo() : c(new int()) {}

    void inc() const {
        *c += 1;
        cout << *c << endl;
    }

   private:
    int* c;
};

int main() {
    Foo f;
    f.inc();
    f.inc();
    f.inc();
}
posted @ 2023-04-05 09:12  Zijian/TENG  阅读(82)  评论(0编辑  收藏  举报