[C++] c++ 私有继承 →→→→→进入此内容的聊天室

来自 , 2021-03-11, 写在 C++, 查看 121 次.
URL http://www.code666.cn/view/d7fd118e
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class ElectricMotor {
  5. public:
  6.         ElectricMotor() {
  7.         }
  8.         ;
  9.         virtual ~ElectricMotor() {
  10.         }
  11.         ;
  12.  
  13. public:
  14.         void StartMotor() {
  15.                 Accelerate();
  16.                 Cruise();
  17.         }
  18.  
  19.         void StopMotor() {
  20.                 cout << "Motor stopped" << endl;
  21.         }
  22.         ;
  23.  
  24. private:
  25.         void Accelerate() {
  26.                 cout << "Motor started" << endl;
  27.         }
  28.  
  29.         void Cruise() {
  30.                 cout << "Motor running at constant speed" << endl;
  31.         }
  32. };
  33.  
  34. class Fan: private ElectricMotor {
  35. public:
  36.         Fan() {
  37.         }
  38.         ;
  39.         ~Fan() {
  40.         }
  41.  
  42.         void StartFan() {
  43.                 StartMotor();
  44.         }
  45.  
  46.         void StopFan() {
  47.                 StopMotor();
  48.         }
  49. };
  50.  
  51. int main() {
  52.         Fan mFan;
  53.  
  54.         mFan.StartFan();
  55.         mFan.StopFan();
  56.  
  57.         /*
  58.          Note: the next two lines access the base class ElectricMotor
  59.          However, as Fan features 'private inheritance' from ElectricMotor,
  60.          neither the base class instance nor its public methods are
  61.          accessible to the users of class Fan.
  62.          Un-comment them to see a compile failure!
  63.          */
  64.         // mFan.Accelerate ();
  65.         // ElectricMotor * pMotor = &mFan;
  66.         return 0;
  67. }
  68.  

回复 "c++ 私有继承"

这儿你可以回复上面这条便签

captcha