现在来看一下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:public 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();
}
编译结果为:
由此可见,对于公有继承而言,基类的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:public 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.showPublic();
b.showProtected();
b.showPrivate();
}
编译结果:
结果正如预测的那样!