本文介绍了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) p>

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

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




  • 使用BaseA,子类不编译,纯虚函数未定义。 li>
  • 使用BaseB,当在BaseB *或Child *上调用foo时,将调用子函数。



解决方案在调用foo时使用Child *而不调用BaseB * div>

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




  • 使用 BaseA ,它将按照预期编译并执行, foo() Child 中虚拟并执行。

  • BaseB 也将按照意图编译和执行, foo()是virtual()并在类 Child li>
  • 使用 BaseC 但是,它将编译并执行,但它将执行 BaseC version如果你从 BaseC Child 版本的上下文中调用它, code> Child


I have three different base classes:

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

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

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

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?

  • With BaseA, the child class doesn't compile, the pure virtual function isn't defined.
  • With BaseB, the function in the child is called when calling foo on a BaseB* or Child*.
  • With BaseC, the function in the child is called when calling foo on Child* but not on BaseB* (the function in parent class is called).

解决方案

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.

  • 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 ++函数覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 04:17