C++ function overriding(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, withfoo()being virtual and executing in classChild. - Same with
BaseB, it will also compile and execute as intended, withfoo()being virtual() and executing in classChild. - With
BaseChowever, it will compile and execute, but it will execute theBaseCversion if you call it from the context ofBaseC, and theChildversion if you call with the context ofChild.
这篇关于C++ 函数重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 函数重写
- GDB 不显示函数名 2022-01-01
- DoEvents 等效于 C++? 2021-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 将 hdc 内容复制到位图 2022-09-04
- 将函数的返回值分配给引用 C++? 2022-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- XML Schema 到 C++ 类 2022-01-01
