簡體   English   中英

C ++繼承,從基類調用派生函數

[英]C++ Inheritance, calling a derived function from the base class

如何從基類調用派生函數? 我的意思是,能夠將一個函數從基類替換為派生類。

防爆。

class a
{
public:
   void f1();
   void f2();
};

void a::f1()
{
   this->f2();
}

/* here goes the a::f2() definition, etc */

class b : public a
{
public:
   void f2();
};

/* here goes the b::f2() definition, etc */    

void lala(int s)
{
  a *o; // I want this to be class 'a' in this specific example
  switch(s)
  {
   case 0: // type b
     o = new b();
   break;
   case 1: // type c
     o = new c(); // y'a know, ...
   break;
  }

  o->f1(); // I want this f1 to call f2 on the derived class
}

也許我采取了錯誤的做法。 任何關於不同設計的評論也將受到贊賞。

在基類中聲明f2()virtual。

class a
{
public:
       void f1();
       virtual void f2();
};

然后,每當派生類重寫f2() ,將根據指針指向的實際對象的類型調用最派生類的版本,而不是指針的類型。

將f2()聲明為虛擬

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM