文档详情

类的合成Composition-湖南大学.PPT

发布:2017-11-13约4.45千字共18页下载文档
文本预览下载声明
Thank you * * * * Introduce 介绍 Introduce 介绍 Introduce 介绍 Introduce 介绍 Introduce 介绍 Introduce 介绍 Introduce 介绍 Introduce 介绍 Introduce 介绍 Introduce 介绍 Introduce 介绍 Introduce 介绍 Introduce 介绍 类的合成 Composition  outlines 对象合成 条件编译 拷贝构造函数 类的合成 Composition 合成 组合 复合 该类的对象中包含其他类型的对象 has a ( is a part of ) 代码重用机制——创建一个包含已有类的新类 优点 被包含对象通过包含他们的类来访问 黑盒重用,因为被包含对象的内部细节是不可见的 很好的封装 每个类专注于一个任务 成员对象 Laptop = CPU + Memeory class Laptop{ public: CPU core; Memory ram; }; Car = Engine + Tires class TCar{ public: TEngine engine; TTire tires[4]; }; //engine.h class TEngine{ //数据成员声明; //成员函数声明; }; 多文件工程 //car.h class TCar{ public: TCar(); TEngine engine; TTire tires[4]; }; int main(){ TCar car; car.description(); } #include “car.h” #include “engine.h” 文件包含中的条件编译 在头文件中使用#ifdef和#ifndef可以防止双重定义的错误。 #ifndef _CAR_H_ #define _CAR_H_ class Car { }; #endif //engine.h class TEngine{ public: TEngine(){ m_manufacturer = 宝马; } void description(){ cout发动机品牌:m_manufacturerendl; } string m_manufacturer; }; //tire.h class TTire{ public: TTire(){ m_manufacturer = 普利司通;} void description(){ cout轮胎品牌: m_manufacturerendl;} string m_manufacturer; }; #include iostream using namespace std; class TCar{ public: TCar(){ cout一台汽车组装成功拉!参数如下:endl; description(); } void description(){ engine.description(); for(int i=0;i4;i++){ cout第 i+1 个 : ; tires[i].description() ;} } TEngine engine; TTire tires[4]; }; TCar的构造函数 ,调用自己的成员方法description()。 成员对象: 一台发动机和四个轮胎. 分别调用成员对象的description()方法来输出相应的信息。 #include engine.h #include tire.h #include iostream #include car.h using namespace std; int main(){ TCar aCar; system(pause); return 0; } 声明TCar类型的对象aCar ,自动调用TCar类的构造函数。 请你为以下实例进行面向对象的设计 一把椅子(Chair)?由一个?椅背(Back)?、一个座位(Seat)和四条腿(?Leg)?组成 一条线段(Line) 有两个端点 (Point) 一篇学位论文(essay)包括封面(cover)、目录(index)、摘要(abstract)、正文(body)和附录
显示全部
相似文档