引言
私有继承在实际使用过程中不多,主要是因为使用共有继承能够很好的支持对象的原有特性,即在对象外部的系列访问和操作。在某些场合,我们只希望访问父类的方法并对访问做了限制,就可能会使用到私用继承(或者保护继承)。
举例
通过下面的程序代码来简单的演示私有继承的使用:
#include <iostream>
class RichMan
{
public:
RichMan() {};
~RichMan() { std::cout << "RichMan Deconstruct\n"; }
void fun() { std::cout << "this is fun in RichMan\n"; }
int add(int num1,int num2) { return num1 + num2; }
virtual void eat() { std::cout << "eat in RichMan\n"; }
int m_company;
private:
int m_money;
int m_car;
protected:
//virtual void eat() { std::cout << "eat in RichMan\n"; }
int m_house;
};
class LittleRichMan :private RichMan
{
public:
LittleRichMan() {
};
~LittleRichMan() { std::cout << "LittleRichMan Deconstruct\n"; }
int sum(int n) {
int result = 0;
for (int i = 0; i < n; i++)
result =