C++ 函数重写 [英] C++ function overriding

查看:40
本文介绍了C++ 函数重写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个不同的基类:

class BaseA
{
public:
    virtual int foo() = 0;
};

class BaseB
{
public:
    virtual int foo() { return 42; }
};

class BaseC
{
public:
    int foo() { return 42; }
};

然后我像这样从基数派生(用 X 代替 A、B 或 C):

I then derive from the base like this (substitute X for A, B or C):

class Child : public BaseX
{
public:
    int foo() { return 42; }
};

三个不同基类中的函数是如何被覆盖的?我的以下三个假设是否正确?还有其他注意事项吗?

How is the function overridden in the three different base classes? Are my three following assumptions correct? Are there any other caveats?

  • 使用 BaseA,子类无法编译,也没有定义纯虚函数.
  • 使用 BaseB,当在 BaseB* 或 Child* 上调用 foo 时,子函数中的函数会被调用.
  • 使用 BaseC,当在 Child* 上调用 foo 而在 BaseB* 上调用 foo 时,子类中的函数会被调用(调用父类中的函数).

推荐答案

在派生类中,如果在基类中定义了virtual,则该方法是virtual,即使派生类的方法中没有使用关键字virtual.

In the derived class a method is virtual if it is defined virtual in the base class, even if the keyword virtual is not used in the derived class's method.

  • 使用 BaseA,它将按预期编译和执行,其中 foo() 是虚拟的并在类 Child 中执行.
  • BaseB 相同,它也会按预期编译和执行,其中 foo() 是 virtual() 并在类 Child 中执行.
  • 然而,使用 BaseC,它会编译和执行,但是如果你从 BaseC 的上下文中调用它,它将执行 BaseC 版本,以及 Child 版本(如果您使用 Child 的上下文调用).
  • With BaseA, it will compile and execute as intended, with foo() being virtual and executing in class Child.
  • Same with BaseB, it will also compile and execute as intended, with foo() being virtual() and executing in class Child.
  • With BaseC however, it will compile and execute, but it will execute the BaseC version if you call it from the context of BaseC, and the Child version if you call with the context of Child.

这篇关于C++ 函数重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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