C ++ const方法对非常量指针成员 [英] C++ const method on non const pointer member

查看:144
本文介绍了C ++ const方法对非常量指针成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何通过const方法保护非const指针成员从一个对象。例如:

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

class B{
    public:
        B(){
            this->val=0;
        }

        void setVal(){
            this->val = 2;
        }

    private:
        int val;
};

class A{
    public:
        A():b(new B){}
        void changeMemberFromConstMethod() const{
            this->b->setVal();
        }
    private:
        B * b; // how to protect data pointed in A::changeMemberFromConstMethod
}

保护A :: b从他的方法指向的数据?
经过许多网络研究,尚未找到满意的答复。

Is it possible to "protect" A::b data pointed from his method? After many research on web, no satisfied reponse found yet.

感谢您的帮助。

推荐答案

这样的东西,可能是:

template <typename T>
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> b = new B;
};

deep_const_ptr 的一个的const方法,并像 T * const T * const >在非const方法中。进一步丰富课程将留给读者。

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.

这篇关于C ++ const方法对非常量指针成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆