c++ 虚拟基类析构顺序
时间: 2023-08-03 07:33:27 浏览: 67
在 C++ 中,虚拟基类的析构顺序是按照虚拟继承的顺序进行的。具体来说,当一个派生类继承了多个虚拟基类时,它们的析构函数会按照被继承的顺序依次被调用,而不是按照派生类中声明的顺序。这是因为在多重继承中,虚拟继承是用来解决菱形继承问题的,因此需要按照虚拟继承链的顺序来调用析构函数以确保正确的对象销毁顺序。
相关问题
派生类析构会调用基类析构吗
定义一个document类,有数据成员name,表示文档名称。从document派生出book类,增加数据成员pagecount,表示书籍页数。在构造函数和析构函数中输出信息,观察基类与派生类的构造函数和析构函数的调用顺序。
代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
class document {
public:
document(const string& name) : name_(name) {
cout << "document constructor called: " << name_ << endl;
}
virtual ~document() {
cout << "document destructor called: " << name_ << endl;
}
protected:
string name_;
};
class book : public document {
public:
book(const string& name, int pagecount) : document(name), pagecount_(pagecount) {
cout << "book constructor called: " << name_ << ", " << pagecount_ << " pages" << endl;
}
~book() {
cout << "book destructor called: " << name_ << ", " << pagecount_ << " pages" << endl;
}
private:
int pagecount_;
};
int main() {
book b("The Lord of the Rings", 1178);
return ;
}
```
输出结果如下:
```
document constructor called: The Lord of the Rings
book constructor called: The Lord of the Rings, 1178 pages
book destructor called: The Lord of the Rings, 1178 pages
document destructor called: The Lord of the Rings
```
可以看到,先调用基类的构造函数,再调用派生类的构造函数;先调用派生类的析构函数,再调用基类的析构函数。
c++重写基类构造函数
在C++中,派生类可以重写基类的构造函数。重写基类构造函数的目的是为了在派生类中初始化基类的数据成员。在派生类的构造函数中,使用基类名::基类构造函数名来调用基类的构造函数。下面是一个例子:
```c++
#include <iostream>
using namespace std;
class Base {
public:
int x;
Base(int a) {
x = a;
}
};
class Derived : public Base {
public:
int y;
Derived(int a, int b) : Base(a) {
y = b;
}
};
int main() {
Derived d(10, 20);
cout << "x = " << d.x << ", y = " << d.y << endl;
return 0;
}
```
输出结果为:
```
x = 10, y = 20
```