C ++继承,从基类中调用派生函数 [英] C++ Inheritance, calling a derived function from the base class

查看:154
本文介绍了C ++继承,从基类中调用派生函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



例。

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

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

/ *这里是a :: f2()定义等* /

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

/ *这里是b :: f2()定义等* /

void lala(int s)
{
a * o; //我想在这个特定的例子中这是类'a'
switch(s)
{
case 0:// type b
o = new b();
休息;
case 1:// type c
o = new c(); //你知道,...
break;
}

o-> f1(); //我想让这个f1在派生类
}



上调用f2也许我' m采取错误的方法。任何关于不同设计的评论也将不胜感激。

解决方案

在基类中声明f2()虚函数。 $ p> class a
{
public:
void f1();
virtual void f2();
};

然后,每当派生类重写 f2()大多数派生类的版本将被调用,取决于指针指向的实际对象的类型,而不是指针的类型。


How can I call a derived function from a base class? I mean, being able to replace one function from the base to the derived class.

Ex.

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
}

Maybe I'm taking a wrong approach. Any comment about different designs around would also be appreciated.

解决方案

Declare f2() virtual in the base class.

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

Then whenever a derived class overrides f2() the version from the most derived class will be called depending on the type of the actual object the pointer points to, not the type of the pointer.

这篇关于C ++继承,从基类中调用派生函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆