私有继承的私有继承作用

如题所述

第1个回答  2016-05-31

私有继承后,基类所有成员在派生类中为private成员。看似没有任何意义,但私有继承可以帮助我们复用基类代码,并防止基类接口的曝光。
看下面一个例子:
#include <iostream>  using std::cout;  using std::endl;
class engine {  public :  void start() {cout << engine->start << endl;}  void move() {cout << engine->move << endl;}  void stop() {cout << engine->stop << endl;}  };
class wheel {  public :  void start() {cout << wheel->start << endl;}  void move() {cout << wheel->move << endl;}  void stop() {cout << wheel->stop << endl;}  };
class car : private engine, private wheel {  public :  void start();  void move();  void stop();  };
void car::start() {  engine::start();  wheel::start();  }
void car::move() {  engine::move();  wheel::move();  }
void car::stop() {  engine::stop();  wheel::stop();  }
int main(int argc, char* argv[]) {  car ca;  ca.start();  ca.move();  ca.stop();  return 0;  }
例子中类car私有继承自类engine和类wheel,类car的三个成员函数start()、move()、stop()分别通过调用类engine和类wheel的成员函数实现,这样做的好处在于不需要重写而直接使用继承自基类的函数,同时因为是私有继承,能通过类car的对象不能直接调用类engine和类wheel的函数,防止不必要函数的曝光,因为对于使用类car对象的用户来说并不需要关心start()、move()、stop()的具体实现过程,也不需要控制engine和wheel的动作。

相似回答