第三次C++实验课

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;
}

 

 

 

本章理解掌握的不是很好,第一题按所有要求写代码编译时出现两个错误解决不了,应该是对各种函数混合使用语法掌握不到位,所以就退而求其次写了一个不符合要求的代码,打算之后再参考同学代码修正。

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值