从派生类调用基本方法 [英] Calling base method from derived class

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

问题描述

我有,例如,这样的类:

I have, for example, such class:

class Base
{
   public: void SomeFunc() { std::cout << "la-la-la\n"; }
};

我从中导出一个新的:

class Child : public Base
{
   void SomeFunc()
   {
      // Call somehow code from base class
      std::cout << "Hello from child\n";
   }
};

我想看看:

la-la-la
Hello from child

我可以从派生类调用方法吗?

Can I call method from derived class?

推荐答案

当然:

void SomeFunc()
{
  Base::SomeFunc();
  std::cout << "Hello from child\n";
}

Btw从 Base :: SomeFunc code>未声明 virtual Derived :: SomeFunc() 隐藏它在基类中,而不是覆盖它,这肯定会导致一些令人讨厌的惊喜从长远来看。所以你可能想把你的声明更改为

Btw since Base::SomeFunc() is not declared virtual, Derived::SomeFunc() hides it in the base class instead of overriding it, which is surely going to cause some nasty surprises in the long run. So you may want to change your declaration to

public: virtual void SomeFunc() { ... }

这会自动使 Derived :: SomeFunc() virtual ,但为了清楚起见,你可能更喜欢显式声明它。

This automatically makes Derived::SomeFunc() virtual as well, although you may prefer explicitly declaring it so, for the purpose of clarity.

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

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