C++ const method on non const pointer member

后端 未结 4 1089
礼貌的吻别
礼貌的吻别 2020-12-19 10:33

I was wondering how protect a non const pointer member from an object throught a const method. For example:

class B{
    public:
        B(){
            thi         


        
4条回答
  •  粉色の甜心
    2020-12-19 11:11

    Something like this, perhaps:

    template 
    class deep_const_ptr {
      T* p_;
    public:
      deep_const_ptr(T* p) : p_(p);
    
      T* operator->() { return p_;}
      const T* operator->() const { return p_;}
    };
    
    class A {
      deep_const_ptr b = new B;
    };
    

    deep_const_ptr behaves like a const T* const pointer in A's const methods, and like T* in non-const methods. Fleshing the class out further is left as an exercise for the reader.

提交回复
热议问题