封闭类对象的创建与消亡p127
#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 << "\tCTyre构造函数" << 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() { return tyre; } }; CCar::CCar() { price = 50010; CTyre(); cout << price << "\tCCar 构造函数 " << 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() { CCar car(48900, 17, 225); cout << "price=" << car.getPrice() << "\tCTyre.Radius=" << car.getCTyre().getRadius() << "\tCTyre.Width=" << car.getCTyre().getWidth() << endl; CCar car1; cout << "price=" << car1.getPrice() << "\tCTyre.Radius=" << car1.getCTyre().getRadius() << "\tCTyre.Width=" << car1.getCTyre().getWidth() << endl; return 0; }
运行结果:
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。