2.编程实验
用C++编程实现以下内容:
(1)习题4-11(教材P144)
要求:设计矩形类是,成员函数除了包括矩形面积的成员函数之外,还包括自定义构造函数、复制构造函数、析构函数。
(2)习题4-20(教材P145)
基于题目要求,给出Complex类的UML类图参考如下:
(1)#include<iostream>
using namespace std;
class Rectangle
{
public:
Rectangle(int l,int w)
{
length=l;
width=w;
}
float getArea()
{
return length*width;
}
private:
int length;
int width;
};
int main()
{ int length;
cout<<"Enter the length of the rectangle:";
cin>>length;
int width;
cout<<"Enter the width of the rectangle:";
cin>>width;
Rectangle rec(length,width);
cout<<"The area is "<<rec.getArea()<<endl;
}
(2)
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(float r1,float i1);
Complex(float r1);
void add(Complex &c);
void show();
private:
float r;
float i;
};
Complex::Complex(float r1,float i1){
r=r1;
i=i1;
}
void Complex::add(Complex &c){
r+=c.r;
i+=c.i;
}
Complex::Complex(float r1)
{
r=r1;
i=0;
}
void Complex::show(){
cout<<r<<(i>0 ? '+':'-')<<i<<'i'<<endl;
}
int main()
{
Complex c1(3,5);
Complex c2=4.5;
c1.add(c2);
c1.show();
return 0;
}
本章理解掌握的不是很好,第一题按所有要求写代码编译时出现两个错误解决不了,应该是对各种函数混合使用语法掌握不到位,所以就退而求其次写了一个不符合要求的代码,打算之后再参考同学代码修正。