/*通过下列代码,打开和注释会发现不同结果,由此可解释基类的析构函数
为什么是虚函数:
理由:如果基类的析构函数不是虚函数,那么析构派生类就会先析构基类
再析构派生类,这显然与析构函数的设计理念不符
结论: 通过结果可得到c++ primer 第五版 555页warning:
在默认情况下,基类默认构造函数初始化派生类对象的基类部分。如果我们
想拷贝(或移动)基类部分,则必须在派生类的构造函数初始值列表中显式
地使用基类的拷贝(或移动)构造函数*/
#include<iostream>
using namespace std;
class A
{
public:
A() { cout << "I'm A Construct" << endl; }
A(int n) { cout << "I'm A Transate Construct" << endl; }
virtual ~A() = default;
private:
int n;
};
class B :public A
{
public:
B() { cout << "I'm B Construct" << endl; }
B(int n)/*:A(n)*/ {cout << "I'm B Translate Construct" << endl;}
private:
int n;
};
int main()
{
B b(2);
system("pause");
return 0;
}
为什么是虚函数:
理由:如果基类的析构函数不是虚函数,那么析构派生类就会先析构基类
再析构派生类,这显然与析构函数的设计理念不符
结论: 通过结果可得到c++ primer 第五版 555页warning:
在默认情况下,基类默认构造函数初始化派生类对象的基类部分。如果我们
想拷贝(或移动)基类部分,则必须在派生类的构造函数初始值列表中显式
地使用基类的拷贝(或移动)构造函数*/
#include<iostream>
using namespace std;
class A
{
public:
A() { cout << "I'm A Construct" << endl; }
A(int n) { cout << "I'm A Transate Construct" << endl; }
virtual ~A() = default;
private:
int n;
};
class B :public A
{
public:
B() { cout << "I'm B Construct" << endl; }
B(int n)/*:A(n)*/ {cout << "I'm B Translate Construct" << endl;}
private:
int n;
};
int main()
{
B b(2);
system("pause");
return 0;
}