基类中的成员是私有成员时的访问方式(P192)
/*
protected访问范围说明符:
基类中的保护成员可以在派生类的成员函数中被访问。
目的:起到隐藏作用,又避免派生类成员函数要访问它们时只能间接访问所带来的麻烦。
注意:
派生类的成员函数只能访问所作用的那个对象(即this指针指向的对象)的基类保护成员,不能访问其他基类对象的基类保护成员。
*/
#include<iostream>
using namespace std;
class BaseClass //基类
{
int v1,v2;
public:
void SetValue(int m,int n)
{
v1=m;
v2=n;
}
void PrintValue();
};
void BaseClass::PrintValue()
{
cout<<"v1="<<v1<<"\tv2="<<v2; //本类中,可以直接访问
}
class DerivedClass:public BaseClass //派生类
{
int v3; //私有成员变量
public:
void SetValue(int m,int n,int k)
{
BaseClass::SetValue(m,n); //通过基类的公有成员函数访问其私有成员变量
v3=k; //本类中,可以直接访问私有成员变量
}
void PrintValue();
};
void DerivedClass::PrintValue()
{
cout<<endl;
BaseClass::PrintValue();
cout<<"\tv3="<<v3<<endl; //直接访问本类中的私有成员变量
}
int main()
{
BaseClass baseCla;
DerivedClass derivedCla;
cout<<"初始时的随机值:"<<endl;
baseCla.PrintValue();
derivedCla.PrintValue();
cout<<"修改基类中的值后"<<endl;
baseCla.SetValue(10,20);
baseCla.PrintValue();
derivedCla.PrintValue();
cout<<"从派生类修改从基类继承的值及本类的值:"<<endl;
derivedCla.SetValue(100,200,300);
baseCla.PrintValue();
derivedCla.PrintValue();
return 0;
}