如何从基类调用派生函数?我的意思是,能够从基类到派生类替换一个函数。

例如

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()。

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

然后,只要派生类覆盖f2(),就会根据指针所指向的实际对象的类型而不是指针的类型来调用最派生类的版本。

07-24 09:46
查看更多