子类中子对象对父类成员的访问

主函数往上5行那里b.a报错,提示 "CBase :: a" 在这一背景下是 protected 的,为什么 子对象 b不能访问父类中的 a变量?


#include <iostream>
using namespace std;
class CBase
{
    protected:
        int a;
    public:
        CBase(int a):a(a)
        {
            cout<<"base structure"<<endl;
        }
        ~CBase()
        {
            cout<<"base destructure"<<endl;
        }
        void print()
        {
            cout<<"a="<<a<<endl;
        }
};
class CDerive : public CBase
{
    private:
        CBase b;
        int c;
    public:
        CDerive(int a, int b,int c) : CBase(a),b(b),c(c)
        {
            cout<<"derive structure"<<endl;
        }
        ~CDerive()
        {
            cout<<"derive destructure"<<endl;
        }
        void print()
        {
            CBase::print();
            cout<<"b.a="<<b.a<<endl;
            cout<<"c="<<c<<endl;
        }
};

int main()
{
    CDerive d(1,2,3);
    d.print();
}


问题是这个a不是你这个对象的父对象啊,是另外Base类的对象

b.a
改成a
CBase b删掉
你的类既然已经继承了父类,自然继承了a这个变量,你不要再搞个父类对象出来