protected 成员继承和使用

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;  //不可以直接访问基类i
b.setI(1); 
}
Child()
{
i = 2;  // 继承了基类i,变成了自己的i,可以访问
}
~Child() {}
};


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


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


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


delete pBase;
delete pBaseOther;

}


注释掉的3行都编译不通过,因为基类的protected变量可以被子类继承,但是不能在基类之外地方被访问。

你可能感兴趣的:(protected 成员继承和使用)