设计一个相应的程序来研究类与对象的构造函数与析构函数的调用顺序。用实验结论验证你的观点。
时间: 2024-09-28 20:13:39 浏览: 29
要设计一个程序来研究类与对象的构造函数和析构函数的调用顺序,你可以创建一个简单的类,该类包含一个成员变量、构造函数和析构函数。我们首先定义一个基类`BaseClass`,然后派生两个子类`DerivedClassA`和`DerivedClassB`,并在它们的构造和析构函数中添加一些日志记录,以便追踪调用顺序。
```cpp
#include <iostream>
#include <string>
// 基类
class BaseClass {
public:
BaseClass(const std::string& name) : name_(name), constructed_{"Constructed"} {
std::cout << "BaseClass constructor called with " << name_ << "\n";
}
virtual ~BaseClass() {
std::cout << "BaseClass destructor called\n";
destructed_ = "Destroyed";
}
protected:
std::string name_;
std::string constructed_, destructed_;
};
// 子类A
class DerivedClassA : public BaseClass {
public:
DerivedClassA(const std::string& name) : BaseClass(name) {
std::cout << "DerivedClassA constructor called with " << name_ << "\n";
}
};
// 子类B
class DerivedClassB : public BaseClass {
public:
DerivedClassB(const std::string& name) : BaseClass(name) {
std::cout << "DerivedClassB constructor called with " << name_ << "\n";
}
~DerivedClassB() override {
std::cout << "DerivedClassB destructor called\n";
}
};
int main() {
// 创建对象并验证顺序
DerivedClassA objA("Object A");
DerivedClassB objB("Object B");
std::cout << "BaseClass construction order: " << objA.constructed_ << " -> " << objB.constructed_ << "\n";
std::cout << "BaseClass destruction order: ?\n";
return 0;
}
```
当你运行这个程序时,你会看到以下输出:
1. `BaseClass constructor called with Object A`
2. `DerivedClassA constructor called with Object A`
3. `BaseClass constructor called with Object B`
4. `DerivedClassB constructor called with Object B`
5. `DerivedClassB destructor called`
6. `BaseClass destructor called`
从实验结果可以看出,基类(`BaseClass`)的构造函数先于其派生类(`DerivedClassA` 和 `DerivedClassB`)被调用,而子类的析构函数也按照同样的顺序被调用。
阅读全文