现在来看一下private,protected,public修饰的成员属性在保护继承的派生类中的可见情况。
#include <iostream>
using namespace std;
/*
类A有三个成员属性,分别是k,i,j,str,以及一些方法;
访问修饰如下:
pubic:
int k;
private:
int i;
protected:
string str;
*/
class A{
public:
int k;
A(int kk,int ii,string s){
k=kk;
i=ii;
str=s;
}
void showPublic(){
cout<<"this is public!"<<endl;
}
private:
int i;
void showPrivate(){
cout<<"this is private!"<<endl;
}
protected:
string str;
void showStr(){
cout<<"str="<<str<<endl;
}
void showProtected(){
cout<<"this is protected!"<<endl;
}
};
//保护继承
class B:protected A
{
public:
B(int i,int j,string s):A(i,j,s){
}
void showMethod(){
A::showPublic();
A::showPrivate();
A::showProtected();
}
void showAttr()
{
cout<<A::k<<endl;
cout<<A::i<<endl;
cout<<A::str<<endl;
}
};
int main()
{
B b(1,2,"hello");
b.showMethod();
b.showAttr();
/*
b.showPublic();
b.showProtected();
b.showPrivate();
*/
}
编译结果为:
这个结果看似和public继承是一样,那么,是否其他的也是一样的呢?看下面的测试:尝试在派生类外直接访问基类成员
#include <iostream>
using namespace std;
/*
类A有三个成员属性,分别是k,i,j,str,以及一些方法;
访问修饰如下:
pubic:
int k;
private:
int i;
protected:
string str;
*/
class A{
public:
int k;
A(int kk,int ii,string s){
k=kk;
i=ii;
str=s;
}
void showPublic(){
cout<<"this is public!"<<endl;
}
private:
int i;
void showPrivate(){
cout<<"this is private!"<<endl;
}
protected:
string str;
void showStr(){
cout<<"str="<<str<<endl;
}
void showProtected(){
cout<<"this is protected!"<<endl;
}
};
//保护继承
class B:protected A
{
public:
B(int i,int j,string s):A(i,j,s){
}
/*
void showMethod(){
A::showPublic();
A::showPrivate();
A::showProtected();
}
void showAttr()
{
cout<<A::k<<endl;
cout<<A::i<<endl;
cout<<A::str<<endl;
}
*/
};
int main()
{
B b(1,2,"hello");
/*
b.showMethod();
b.showAttr();
*/
b.showPublic();
b.showProtected();
b.showPrivate();
}
编译结果为:
可以看到,基类的public成员也不能直接访问了!而在public继承中,时可以在类外直接访问基类的public成员的!
这是为什么?原因是使用保护继承时,基类的公有成员和保护成员都会变成派生类的保护成员。这就是保护继承和公有继承的最主要区别。貌似其他的木有区别0.0。