gpt4 book ai didi

C++ 构造函数/析构函数继承

转载 作者:IT老高 更新时间:2023-10-28 13:24:25 25 4
gpt4 key购买 nike

编辑:答案摘要

在下文中,B 是 A 的子类。

这是一个术语问题; ctor 和 dtor 是继承的,即 B 的 ctor/dtor 不会从 A 的接口(interface)借用。一个类至少有一个构造函数,并且只有一个析构函数。

  • 构造函数:
    • B 不从 A 继承构造函数;
    • 除非 B 的 ctor 显式调用 其中一个 A 的 ctor,否则来自 A 的默认 ctor 将在 B 的 ctor 主体之前自动调用(想法是 A 需要初始化在创建 B 之前)。
  • 析构函数:
    • B 不继承 A 的 dtor;
    • 退出后,B的析构函数会自动调用A的析构函数。

致谢:我要特别感谢 Oli Charlesworth 和 Kos 的回答,我将 Kos 的答案设置为解决方案,因为这是我最了解的答案。


原帖

当您在 Google 上搜索“C++ 析构函数继承站点:stackoverflow.com”时,您目前会发现以下帖子:

  1. Constructor and Destructor Inheritance : 两个声望超过 30k 的用户说它是继承的,而不是继承的
  2. Are virtual destructors inherited? : 这里没有提到任何指向析构函数未被继承的内容
  3. Destructors and inheritance in C++? :评论似乎表明析构函数是继承的

Q1:我从实践中也知道,如果没有明确定义派生类的构造函数,就不能使用与父构造函数相同的原型(prototype)来初始化派生对象,对吗?


尽管从帖子中可以清楚地看出析构函数似乎是继承的,但我仍然对拥有 32k 声誉的用户会说它不是这一事实感到困惑。我写了一个小例子,应该可以澄清大家的想法:

#include <cstdio>

/******************************/

// Base class
struct A
{
A() { printf( "\tInstance counter = %d (ctor)\n", ++instance_counter ); }
~A() { printf( "\tInstance counter = %d (dtor)\n", --instance_counter ); }

static int instance_counter;
};

// Inherited class with default ctor/dtor
class B : public A {};

// Inherited class with defined ctor/dtor
struct C : public A
{
C() { printf("\tC says hi!\n"); }
~C() { printf("\tC says bye!\n"); }
};

/******************************/

// Initialize counter
int A::instance_counter = 0;

/******************************/

// A few tests
int main()
{
printf("Create A\n"); A a;
printf("Delete A\n"); a.~A();

printf("Create B\n"); B b;
printf("Delete B\n"); b.~B();

printf("Create new B stored as A*\n"); A *a_ptr = new B();
printf("Delete previous pointer\n"); delete a_ptr;

printf("Create C\n"); C c;
printf("Delete C\n"); c.~C();

}

这是输出(使用 g++ 4.4.3 编译):

Create A
Instance counter = 1 (ctor)
Delete A
Instance counter = 0 (dtor)
Create B
Instance counter = 1 (ctor)
Delete B
Instance counter = 0 (dtor)
Create new B stored as A*
Instance counter = 1 (ctor)
Delete previous pointer
Instance counter = 0 (dtor)
Create C
Instance counter = 1 (ctor)
C says hi!
Delete C
C says bye!
Instance counter = 0 (dtor) // We exit main() now
C says bye!
Instance counter = -1 (dtor)
Instance counter = -2 (dtor)
Instance counter = -3 (dtor)

Q2:任何认为它不是遗传的人可以解释一下吗?

Q3:那么当你调用带有输入的子类的构造函数时会发生什么?是否也调用了父类(super class)的“空构造函数”?

最佳答案

术语,术语...

好的,“Foo 是继承的”是什么意思?我们的意思是,如果类 A 的对象在其接口(interface)中有 Foo,那么类 B 的对象是 A< 的子类 在其界面中也有 Foo

  • 构造函数不是对象接口(interface)的一部分。它们直接属于类。 AB 类可以提供完全不同的构造函数集。这里没有“被继承”。

    (实现细节:每个B的构造函数调用一些A的构造函数。)

  • 析构函数确实是每个对象接口(interface)的一部分,因为对象的用户负责调用它们(即直接使用 delete 或通过让对象间接调用超出范围)。 每个对象只有一个析构函数:它自己的析构函数,可以选择是虚拟析构函数。它始终是它自己的,它不会被继承。

    (实现细节:B的析构函数调用A的析构函数。)

所以:基构造函数和派生构造函数和析构函数之间存在联系,但这不像“它们是继承的”。

我希望这能回答你的想法。

关于C++ 构造函数/析构函数继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14184341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com