实验3 类与对象的设计
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
实验3 类与对象的设计
专业:计算机科学与技术班级:10计本1班学号:姓名:
实验地点:B102实验时间:2011/10/18 指导教师:李佐勇
一、实验目的
1.掌握声明类的方法,类和类成员的概念以及定义对象的方法;
2.初步掌握利用类和对象的概念进行面向对象程序开发的方法;
3.掌握构造函数、复制构造函数、析构函数的定义与使用;
4.理解类的组合以及组合类构造函数的定义与使用。
二、实验环境
一台PC机,Windows XP操作系统,Visual C++ 6.0开发环境。
三、实验内容
1.Lab3_1.cpp:定义并实现一个矩形类(rectangle),其包含数据成员:长(length)、宽(width);函数成员:Show_length (显示矩形的长度)、Show_width (显示矩形的宽度)、Get_area (计算矩形的面积),除了上述成员函数,自行思考构造函数的设计。
2.Lab3_2.cpp:定义一个满足课后题目4-20要求的复数类Complex。
(注意:题目1、2选作一题即可)
3.Lab3_3.cpp:定义CPU类,其包含数据成员:主频(frequency)、字长(wordlength)、倍频系数(coefficient)。其中,字长为枚举型enum cpu_wordlen={W16,W32,W64,W128,W256},frequency为float型,coefficient为double型。此外,类的公有成员函数run和stop分别提示CPU的运行与停止。请给出构造函数(带参数、不带参数)、拷贝构造函数、析构函数、run、stop函数的定义,并在函数体内给出相应的提示便于观察程序运行过程,结合实验理解构造函数、拷贝构造函数、析构函数的调用顺序。
4.Lab3_4.cpp:请结合组合类的概念来描述计算机类Computer,其包含数据成员:芯片(cpu)、内存(ram)、显示器(monitor);函数成员:run:提示计算机正在运行、stop:提示计算机停止工作、用户自定义的构造函(有参数、无参数)。芯片cpu是lab3_2中CPU类的对象,内存ram是单位为M的整型数据,显示器Monitor为屏幕对角线英寸的整型数据。请写出类Computer的定义以及各个成员函数的实现,并在每个成员函数的函数体中给出相应的提示便于观察程序运行过程。观察构造函数和复制构造函数的调用顺序。
四、实验记录
1. #include
using namespace std;
class rectangle{
public:
void show_length(float x);
void show_width(float y);
void get_area(float x,float y);
private:
float x,y;
};
inline void rectangle::show_length(float x){
cout<<"The length of the rectangle is:"< } inline void rectangle::show_width(float y){ cout<<"The width of the rectangle is:"< } inline void rectangle::get_area(float x,float y){ cout<<"The area of the rectangle is:"< } int main() { rectangle rec1; rec1.show_length(0); rec1.show_width(0); rec1.get_area(0,0); rectangle rec2; rec2.show_length(5); rec2.show_width(4); rec2.get_area(5,4); return 0; 3.#include using namespace std; enum cpu_wordlen {w16,w32,w64,w128,w256}; enum cpu_wordlen wordlength; class CPU{ public: CPU (float freq,double coef,enum cpu_wordlen wordl); CPU(){ frequency=0; coeffcient=0; wordlength=cpu_wordlen(w16); } CPU(CPU&p); void run(); void stop(); float getF(){ return frequency; } double getC(){ return coeffcient; } enum cpu_wordlen getW(){ return wordlength; } private: float frequency; double coeffcient; cpu_wordlen wordlength; }; CPU::CPU(float freq,double coef,enum cpu_wordlen wordl){ frequency=freq; coeffcient=coef; wordlength=wordl; } CPU::CPU(CPU&p){ frequency=p.frequency; coeffcient=p.coeffcient; wordlength=p.wordlength; } void run(){ cout<<"CPU is running!"< } void stop(){ cout<<"CPU stopped!"< } void fun1(){ cout<<"Call a funcrion of parametres!"< } void fun2(){ cout<<"Call a function without of parametres!"< } void fun3(CPU p){ cout<<"frequency="< } void fun4(CPU p){ cout<<"coeffcient="< } void fun5(CPU p){ cout<<"wordlength="< } int main(){ fun1(); CPU c1(25,5,w32); fun3(c1); fun4(c1); fun5(c1); run();