河北工业大学 c 实验报告实验四.pdfVIP

  • 34
  • 0
  • 约1.1万字
  • 约 15页
  • 2017-05-21 发布于浙江
  • 举报
河北工业大学 c 实验报告实验四

1、编写一个程序,要求: (1)生明一个类Complex (复数类),定义类Complex 的两个对象c1和c2, 对象c1通过构造函数直接指定复数的实部和虚部 (类私有数据成员为double类 型:real 和imag)为2.5及3.7,对象c2 通过构造函数直接指定复数的实部和虚 部为4.2 及6.5; (2)定义友元运算符重载函数,它以c1、c2 对象为参数,调用该函数时能 返回两个复数对象相加操作; (3)定义成员函数print,调用该函数时,以格式 “real+imag i”输出当前 对象的实部和虚部,例如:对象的实部和虚部分别是4.2 和6.5,则调用print 函 数输出格式为:4.2+6.5i; 4 c1 c2 ()编写主程序,计算出复数对象 和 相加结果,并将其结果输出。 #includeiostream usingnamespace std; classComplex { public: Complex(doubler 0.0,doublei 0.0); friend Complex operator+ (Complex a,Complexb); voidprintf(); private: doublereal; doubleimag; }; Complex::Complex(doubler,doublei) { real r; imag i; } Complex operator+ (Complex a,Complexb) { Complextemp; temp.real a.real+b.real; temp.imag a.imag+b.imag; returntemp; } void Complex::printf() { coutreal; if(imag0) cout+; if(imag! 0) coutimagiendl; } voidmain() { Complex c1(2.5,3.7),c2(4.2,6.5),c3; c3 c1+c2; c3.printf(); } 2、编写一个程序,其中设计一个时间类Time,用来保存时、分、秒等私有 数据成员,通过重载操作符 “+”实现两个时间的相加。要求将小时范围限制在 大于等于0,分钟范围限制在0~59 分,秒钟范围限制在0~59秒。 提示:时间类Time 的参考框架如下: classTime { public: Time(inth 0,intm 0,int s 0);//构造函数 Timeoperator+(Time);//运算符重载函数,实现两个时间的相加 voiddisptime();//显示时间函数 private: inthours,minutes,seconds; }; #includeiostream usingnamespace std; classTime { public: Time(inth 0,intm 0,int s 0);//构造函数 Timeoperator+(Time );//运算符重载函数,实现两个时间的相加 voiddisptime();//显示时间函数 private: inthours; int minutes; int seconds; }; Time::Time(inth,intm,int s) { hours h; minutes m; seconds s; } TimeTime::operator+(Timet) { inth,m,s; s (t.seconds+seconds)%60; m (minutes+t.minutes+(t.seconds+seconds)/60)%60; h hours+t.hours+(minutes+t.

文档评论(0)

1亿VIP精品文档

相关文档