一、实验内容
1. 设计并测试一个类CRectangle,要求如下所述。
(1) 该类中的私有成员变量存放Rectangle的长和宽。
(2) 用构造函数及成员函数setLW()来设置长和宽的值。
(3) 求周长及面积。
2. 创建一个名为Complex的类,进行复数的算术运算。编写一个测试程序来测试该类。复数的形式为:
realpart+imaginarypart*i
其中i为:
用浮点变量表示类中的private数据。提供一个构造函数,能够对所声明的该类对象进行初始化。在一提供初始化值的情况下,该构造函数应包含默认值。针对以下各种功能,分别提供一个public成员函数。
a) 两个复数相加:实部与实部相加,虚部与虚部相加。
b) 两个复数相减:左侧操作数的实部减去右侧操作数的实部,左侧操作数的虚部减去右侧操作数的虚部
c) 用(a, b)的形式打印复数,其中a是实部,b是虚部。
示例输出
二、实验目的
1. 掌握类、类的数据成员、类的成员函数的定义方式。
2. 理解类成员的访问控制方式。
3. 掌握对象的定义和操作对象的方法。
4. 理解构造函数和析构函数的定义与执行过程。
5. 理解面向对象的价值。
三、主要仪器设备及耗材
硬件:计算机一台
软件:VC++ 6.0,MSDN2003或者以上版本
四、实验步骤
1. 创建空白新工程,向新工程中添加空文件
2. 编写代码
3. 编译、调试并运行
五、实验数据及处理结果
试验内容(1)的相关代码:
CRtangle.H文件的代码:
#include<iostream>
using namespace std;
class CRtangle
{
public :
CRtangle(float x=3,float y=4){length=x;width=y;}
void setLW(float m, float n){length=m;width=n;}
void show(){cout<<”length=”<<length<<”,width=”<<width<<endl;}
float area();
float circle();
~CRtangle(){cout<<”good”<<endl;};
private :
float length ,width;
};
float CRtangle:: area()
{
return length*width;
};
float CRtangle:: circle()
{
return 2*(length+width);
};
Main函数代码:
#include<iostream>
#include”CRtangle.h”
using namespace std;
void main()
{
CRtangle Rtangle1,Rtangle2(2.4,3.4);
Rtangle1.show();
cout<<Rtangle1.area()<<Rtangle1.circle()<<endl;
Rtangle2.show();
cout<<Rtangle2.area()<<Rtangle2.circle()<<endl;
}
试验内容(2)相关代码:
complex.H文件代码:
#include<iostream>
using namespace std;
class complex
{
public:
complex(double r=0.0,double i=0.0){ real=r; imag=i;}
void display();
complex operator +(complex c2);
complex operator -(complex c2);
private:
double real;
double imag;
};
complex complex:: operator +(complex c2)
{
return complex(real+c2.real,imag+c2.imag);
}
complex complex:: operator -(complex c2)
{
return complex(real-c2.real,imag-c2.imag);
}
void complex:: display()
{
cout<<”(“<<real<<”,”<<imag<<”)”;
}
Main函数:
#include<iostream>
#include”complex.h”
using namespace std;
void main()
{
complex c1(3.2,1.2),c2(4.5,3.6),c3;
c3=c1+c2;
c1.display();
cout<<”+”;
c2.display();
cout<<”=”;
c3.display();
c3=c1-c2;
c1.display();
cout<<”-”;
c2.display();
cout<<”=”;
c3.display();
}
六、思考讨论题或体会或对改进实验的建议