编辑:答案摘要
在下文中,B是A的子类.
这是一个术语问题; ctors和dtor 不是继承的,因为B的ctor/dtor 不会从A的界面借用.一个类至少有一个构造函数,并且只有一个析构函数.
致谢: 我特别感谢Oli Charlesworth和Kos的答案,我将Kos的答案作为解决方案,因为这是我最了解的答案.
原始邮政
当您在Google上搜索"C++析构函数继承站点:stackoverflow.com"时,您当前会发现以下帖子:
Q1:我从实践中也知道的是,你不能使用与它的父构造函数相同的原型初始化派生对象而没有明确地定义派生类的构造函数,这是正确的吗?
尽管从帖子中可以清楚地看出析构函数似乎是继承的,但我仍然感到困惑的是,拥有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 …Run Code Online (Sandbox Code Playgroud)