|
发表于 2020-11-13 08:40:43
|
显示全部楼层
本楼为最佳答案
本帖最后由 xieglt 于 2020-11-13 08:55 编辑
解释在注释里头
- #include<iostream>
- using namespace std;
- class Ctyre //轮胎类
- {
- private:
- int radius; //半径
- int width; // 宽度
-
- public:
- Ctyre() :radius(16), width(185)
- {
- cout << radius << "\tCtyre 构造函数" << endl;
-
- }
- Ctyre(int r, int w) :radius(r), width(w)
- {
- cout << radius << " \t Ctyre 构造函数 " << endl;
-
- }
-
- ~Ctyre()
- {
- cout << radius << "\tCtyre 析构函数" << endl;
-
- }
- int getRadius()
-
- {
- return radius;
-
- }
- int getWidth()
- {
- return width;
-
- }
- };
- class Ccar //汽车类
- {
- private:
- int price; // 价格
-
- Ctyre tyre;
-
- public:
- Ccar();
-
- Ccar(int p, int tr, int tw);
-
- ~Ccar();
- int getPrice()
- {
- return price;
- }
-
- //这里应该写成 Ctyre & getCtyre() 返回引用,即返回成员变量的地址
- //否则,编译器将在栈上构造一个临时的 Ctyre 对象
- Ctyre getCtyre()
- {
- return tyre;
- }
-
-
- };
- Ccar::Ccar()
- {
- //这里调用 ctyre 会构造一个对象,另外还会构造一个成员变量 tyre 这里是构造 2 个
- price = 50010; Ctyre(); cout <<price << " \t Ccar 构造函数" << endl;
- }
- Ccar::Ccar(int p, int tr, int tw) : price(p), tyre(tr, tw)
- {
- cout << price << " \tCcar 构造函数 " << endl;
-
-
-
- }
- Ccar::~Ccar()
- {
- cout << price << "\tCcar 析构函数" << endl;
- }
- int main()
- {
- //这里构造了一个 Ctyre 对象 +1
- Ccar car(48900, 17, 225);
-
- cout << " price =" << car.getPrice();
- //这里构造了 2个临时 Ctyre 对象 + 2 ,
- //这两个临时对象走的是 拷贝构造函数 或者 = 重载函数 ,你没有定义,编译器自己帮你定义了
- //Ctyre(const Ctyre &)
- //Ctyre & operator = (const Ctyre &)
- cout << "\t Ctyre .radius = " << car.getCtyre().getRadius()
- << " \tCtyre .width = " << car.getCtyre().getWidth() << endl;
-
- //这里构造了 2个 Ctyre 对象 +2
- Ccar car1;
- cout << " price =" << car1.getPrice();
- //这里构造了2个临时 Ctyre 对象 +2
- //这两个临时对象走的是 拷贝构造函数 或者 = 重载函数
- cout << "\t Ctyre .radius = " << car1.getCtyre().getRadius()
- << " \tCtyre .width = " << car1.getCtyre().getWidth() << endl;
-
- //总共是 7 个 Ctyre 对象,你数一数析构输出看对不对
- return 0;
- }
复制代码 |
|