access private members in inheritance

后端 未结 6 1358
余生分开走
余生分开走 2021-01-31 17:23

I have a class A, which have a field val declared as private. I want to declare a class B, that inherit from A and have an access to val. Is there a way to do it on C++?

<
6条回答
  •  南方客
    南方客 (楼主)
    2021-01-31 17:36

    You can access the private members of a base class say A through an inherited member function of A

    #include
    using namespace std;
    
    class A{
        int a;
        
        public:
        A(){};
        A(int val){a=val;};
        
        int get_a(){//To access a private variable it must be initialized here
            a=10;
            return a;
        }
    };
    
    class B: public A{
        int b;
        
        public:
        B(){};
        B(int val){b=val;};
        
        void get(){
            cout<

提交回复
热议问题