qfedu-cpp-level/day3/d12.cpp

49 lines
774 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.

// 多个对象的构造和析构
// 类对象作为成员
#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)
{
cout << "B(int x)" << endl;
}
~B() // A 的对象在 B 的空间中A 对象在 B 空间释放之后就失效,失效也会释放空间(调用析构函数)
{
cout << "~B()" << endl;
}
private:
A a; // A 类的对象作为 B 类的成员
};
int main()
{
B b1;
return 0;
}