河北工业大学_C++实验报告实验四.doc

  1. 1、本文档共16页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
. . . .......... 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.5 i; (4)编写主程序,计算出复数对象c1和c2相加结果,并将其结果输出。 #includeiostream using namespace std; class Complex { public: Complex(double r=0.0,double i=0.0); friend Complex operator+ (Complex a,Complex b); void printf(); private: double real; double imag; }; Complex::Complex(double r,double i) { real=r; imag=i; } Complex operator+ (Complex a,Complex b) { Complex temp; temp.real=a.real+b.real; temp.imag=a.imag+b.imag; return temp; } void Complex::printf() { coutreal; if(imag0) cout+; if(imag!=0) coutimagiendl; } void main() { 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的参考框架如下: class Time { public: Time(int h=0,int m=0,int s=0);//构造函数 Time operator+(Time );//运算符重载函数,实现两个时间的相加 void disptime();//显示时间函数 private: int hours,minutes,seconds; }; #includeiostream using namespace std; class Time { public: Time(int h=0,int m=0,int s=0);//构造函数 Time operator+(Time );//运算符重载函数,实现两个时间的相加 void disptime();//显示时间函数 private: int hours; int minutes; int seconds; }; Time::Time(int h,int m,int s) { hours=h; minutes=m; seconds=s; } Time Time::operator+(Time t) { int h,m,s; s=(t.seconds+seconds)%60; m=(minutes+t.minutes+(t.seconds+seconds)/60)%60; h=hours+t.hours+(minutes+t.minutes+(t.seconds+seconds)/60)/60; hours=h; minutes=m; seconds=s; return *this; } void Time::disptime() { couthours:minutes:seconds.endl; } void Input(int h,int m,int s) { cout输入时间:; cinh ; cinm ; cins ; while(m0||m59||s0||s59) { cout******时间输入错误!请重新输 !****

文档评论(0)

xfnzn + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档