#include "stdafx.h"
#include <iostream>
using namespace std;
/*
私有继承的两个原则:
(1)、和公有继承相反,如果两个类之间的继承关系为私有,编译器一般不会将派生类对象(如Child)转换成基类对象(如Parent)
(2)、从私有基类继承而来的成员都成为了派生类的私有成员,即使它们在基类中是保护或公有成员
大家可以看出私有继承时派生类与基类不是“is a”的关系,而是意味着“Is-Implement-In-Terms-Of”(以…实现)。
如果使类D私有继承于类B,这样做是因为你想利用类B中已经存在的某些代码,而不是因为类型B的对象和类型D的对象之间有什么概念上的关系。
因此,私有继承在软件“设计”过程中毫无意义,只是在软件“实现”时才有用。
*/
class Parent
{
public:
Parent(){}
Parent(int a):m_a(a){}
virtual void print()
{
cout<<"Parent::"<<m_a<<endl;
}
private:
int m_a;
};
//私有继承
class Child : private Parent
{
public:
Child(){}
Child(int a, int b):Parent(a),m_b(b){}
void print()
{
Parent::print();
cout<<"Child::"<<m_b<<endl;
}
private:
int m_b;
};
//全局函数
void Print(Parent &p)
{
p.print();
}
int main()
{
Parent p(1);
Child c(1,3);
Print(p);
Print(c);//编译错误(类型转换”: 从“Child *”到“Parent &”的转换存在,但无法访问),由此可见私有继承不能用于多态
p = c;//编译错误(“类型转换”: 从“Child *”到“const Parent &”的转换存在,但无法访问)
}