C++语法基础--public,protected,private的继承方式及其访问性

古城微笑少年丶 2021-12-20 18:31 311阅读 0赞

*派生类所继承的成员的访问由基类中的成员访问级别和派生列表中使用的访问标号共同控制
*派生类可以进一步限制,但不能放松对所继承的成员的访问
*基类本身指定对自身成员的最小访问控制

1.基类成员为private

*\只有基类和基类的友元可以访问该成员,派生类不能直接访问基类的private成员

2.基类成员为public或protected,则派生列表中使用的访问标号决定该成员在派生类中的访问级别
*公用继承:基类成员保持自己的访问级别
*受保护继承:基类的public和protected成员在派生类中为protected成员
*私有继承:基类的所有成员在派生类中为private成员

Example:
class base
{
public:
base(int i=0,int j=0,int k=0):x(i),y(j),z(k)
{

}

void func()
{
cout<<”base.func():”<<endl;
cout<<”x: “<<x<<”\t”<<”y: “<<y<<”\t”<<”z: “<<z<<endl;//ok
}
public:
int x;
protected:
int y;
private:
int z;
};

class public_derived:public base
{
public:
public_derived(int i,int j,int k):base(i,j,k)
{
}

void func()
{
cout<<”public_derived.func()”<<endl;
cout<<”x: “<<x<<endl;
cout<<”y: “<<y<<endl;//ok
//cout<<”z: “<<z<<endl; //error’int base::z’ is private
}
};

class protected_derived:protected base
{
public:
protected_derived(int i,int j,int k):base(i,j,k)
{

}
void func()
{
cout<<”protected_derived.func()”<<endl;
cout<<”x: “<<x<<endl;
cout<<”y: “<<y<<endl;//ok
//cout<<”z: “<<z<<endl;//error’int base::z’ is private
}
};

class private_derived:private base
{
public:
private_derived(int i,int j,int k):base(i,j,k)
{
}

void func()
{
cout<<”private_derived.func()”<<endl;
cout<<”x: “<<x<<endl;
cout<<”y: “<<y<<endl;//ok
//cout<<”z: “<<z<<endl;//error’int base::z’ is private
}
};

下面的main函数将测试派生类内部对基类成员的可访问性
int main()
{
base b(1,1,1);
b.func();
public_derived public_d(2,2,2);
public_d.func();
protected_derived protected_d(3,3,3);
protected_d.func();
private_derived private_d(4,4,4);
private_d.func();

return 0;
}

运行结果:
Center

Tips:对于派生类
*基类的private成员都是不可访问的
*基类的protected,public成员都是可以直接访问的

现在修改main函数,测试派生类对象对基类成员的可访问性
int main()
{
base b(1,1,1);
cout<<”base::”<<endl;
cout<<b.x<<endl;//ok
//cout<<b.y<<endl;//error, ‘int base::y’ is protected
//cout<<b.z<<endl;//error, ‘int base::z’ is private

cout<<”public_derived::”<<endl;
public_derived public_d(2,2,2);
cout<<public_d.x<<endl;
//cout<<public_d.y<<endl;//error, ‘int base::y’ is protected
//cout<<public_d.z<<endl;//error, ‘int base::z’ is private

cout<<”protected_derived::”<<endl;
protected_derived protected_d(3,3,3);
//cout<<protected_d.x<<endl;//error,’int base::x’ is inaccessible
//cout<<protected_d.y<<endl;//error, ‘int base::y’ is protected
//cout<<protected_d.z<<endl;//error, ‘int base::z’ is private

cout<<”private_derived::”<<endl;
private_derived private_d(4,4,4);
//cout<<private_d.x<<endl;//error ‘int base::x’ is inaccessible
//cout<<private_d.y<<endl;//error, ‘int base::y’ is protected
//cout<<private_d.z<<endl;//error, ‘int base::z’ is private

return 0;
}

运行结果:
Center 1

Tips:对于派生类的对象
*只能访问基类的public成员,基类的protected,private成员都不可访问**

发表评论

表情:
评论列表 (有 0 条评论,311人围观)

还没有评论,来说两句吧...

相关阅读