qfedu-cpp-level/day3/d13.cpp

51 lines
891 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 多个对象的构造和析构
// 类对象作为成员
// d12 的改造测试
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "A()" << endl;
}
A(int x)
{
cout << "A(int x)" << endl;
}
~A()
{
cout << "~A()" << endl;
}
};
class B
{
public:
B() // 构造函数用于初始化成员数据,说明成员变量先创建
{
cout << "B()" << endl;
}
// 成员名:(参数名)
B(int x) : a(x) // 指定 a 对象的构造函数进行数据初始化
{
cout << "B(int x)" << endl;
}
~B() // A 的对象在 B 的空间中A 对象在 B 空间释放之后就失效,失效也会释放空间(调用析构函数)
{
cout << "~B()" << endl;
}
private:
A a; // A 类的对象作为 B 类的成员
};
int main()
{
B b1(1);
return 0;
}