您的位置:首页 > 编程语言 > C语言/C++

C++学习笔记13,private继承,私有继承(四)

2014-05-26 10:31 363 查看
最后来看一下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:private 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();
*/
}
编译结果:



结果和前面的都是一样的。那么在派生类类外的可见性呢?

测试例子:

#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:private 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:
A(){}
void showPublic(){
cout<<"this is public!"<<endl;
}
};
//私有继承
class B:private A
{
public:
B(){

}
};
class C:public B
{
public:
C(){}
};
int main()
{
C c;
c.showPublic();

}
编译结果:



结果正好印证了上面的结论。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++