C++ const method on non const pointer member

后端 未结 4 1095
礼貌的吻别
礼貌的吻别 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:06

    If you change the member of A from

        B* b;
    

    to

        B b;
    

    then you will get the expected behavior.

    class A{
        public:
            A() : b() {}
    
            void changeMemberFromConstMethod() const{
                this->b.setVal(); // This will produce a compiler error. 
            }
        private:
            B b;
    }
    

提交回复
热议问题