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
.
相关文章