C++私有继承

当遇到

class A : private B
{...};

就是私有继承,它有一些特性:基类的成员会成为派生类的私有成员,所以有如下示例

#include <cstdlib>
#include <iostream>

using namespace std;

class Engine
{
public:
   Engine(int numCylinders) {}
   void start() {cout << "start" << endl;}         
};


class Car : public Engine
{
public:
   Car() : Engine(8) {}
   //using Engine::start; 
};


int main(int argc, char *argv[])
{
  Car c;
  c.start();
  system("PAUSE");
  return EXIT_SUCCESS;
}

要想让c.start()执行,就要有using Engine::start。(补:Car() : Engine(8) {} 相当于java继承机制中的super用法)

此外私有继承还有一个特性:派生类对象不能向上转型为基类对象,即不能出现Engine e = (Engine) c。

通常,应使用包含来建立has-a关系,如果新类需要访问原有类的保护成员,或需要重新定义虚函数,则应使用私有继承。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值