基类的protected成员变量只能被子类继承,在基类之外都不能直接访问基类protected成员变量

#include "iostream"


using namespace std;


class Base

{
public:
Base() {}
~Base() {}


void setI(int a) {i = a;}
int getI() {return i;}


protected:
int i;
};


class Child : public Base
{
public:
Child(Base& b)
{
//b.i = 1; // 在base类外不能访问base类的protected成员变量
b.setI(1); 
}
Child()
{
i = 2; //子类继承了基类的protected成员变量
}
~Child() {}
};


void main()
{
Base* pBase = new Base();
Child child(*pBase);


cout << pBase->getI() << endl;


Base* pBaseOther = new Child();
cout << pBaseOther->getI() << endl;


delete pBase;
delete pBaseOther;
}

你可能感兴趣的:(基类的protected成员变量只能被子类继承,在基类之外都不能直接访问基类protected成员变量)