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
BaseC
however, it will compile and execute, but it will execute theBaseC
version if you call it from the context ofBaseC
, and theChild
version if you call with the context ofChild
.
这篇关于C++ 函数重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 函数重写


基础教程推荐
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01