基本析构函数真的可以被 C++ 中的派生析构函数覆盖吗?
Can a base destructor really be overridden by a derived destructor in C++?
在整个网络上,以及 Bjarne Stroustrup 的 C++ 书中,我看到这样的陈述,"If a base destructor is declared virtual then it is overridden by a derived class's destructor."
但是,为什么叫覆盖呢?它与覆盖函数的 "usual" 方式略有不同吗?通常,我指的是派生 class 中的典型虚函数,共享与基类中的方法签名相同的方法签名。在这种通常情况下,根据指针指向的实际对象,会忽略基础版本或派生版本……我们不要详细讨论通常意义上的重写是如何工作的。
但在析构函数的情况下,基础析构函数 最终将 调用,无论如何。此外,它的名称也不同。为什么叫overriding?
Why is it then called overriding?
因为它覆盖了基类的析构函数class。
考虑一下:
struct Foo
{
~Foo() {}
};
struct Bar : Foo
{
~Bar() {} // This does not override ~Foo.
};
Foo* fptr = new Bar;
delete fptr; // ~Foo() is called.
~Bar()
如果指针是 Bar*
将被调用。
Bar* bptr = new Bar;
delete bptr; // ~Bar() is called.
但是,如果您将 Foo
更改为:
struct Foo
{
virtrual ~Foo() {}
};
struct Bar : Foo
{
~Bar() {} // This overrides ~Foo.
};
然后使用
Foo* fptr = new Bar;
delete fptr; // ~Bar() is called.
// ~Bar() overrides ~Foo().
在整个网络上,以及 Bjarne Stroustrup 的 C++ 书中,我看到这样的陈述,"If a base destructor is declared virtual then it is overridden by a derived class's destructor."
但是,为什么叫覆盖呢?它与覆盖函数的 "usual" 方式略有不同吗?通常,我指的是派生 class 中的典型虚函数,共享与基类中的方法签名相同的方法签名。在这种通常情况下,根据指针指向的实际对象,会忽略基础版本或派生版本……我们不要详细讨论通常意义上的重写是如何工作的。
但在析构函数的情况下,基础析构函数 最终将 调用,无论如何。此外,它的名称也不同。为什么叫overriding?
Why is it then called overriding?
因为它覆盖了基类的析构函数class。
考虑一下:
struct Foo
{
~Foo() {}
};
struct Bar : Foo
{
~Bar() {} // This does not override ~Foo.
};
Foo* fptr = new Bar;
delete fptr; // ~Foo() is called.
~Bar()
如果指针是 Bar*
将被调用。
Bar* bptr = new Bar;
delete bptr; // ~Bar() is called.
但是,如果您将 Foo
更改为:
struct Foo
{
virtrual ~Foo() {}
};
struct Bar : Foo
{
~Bar() {} // This overrides ~Foo.
};
然后使用
Foo* fptr = new Bar;
delete fptr; // ~Bar() is called.
// ~Bar() overrides ~Foo().