版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter5OperatorOverloading1.Markthefollowingstatermentsastrue(T)orfalse(F)andgivereasons.(1)C++allowsoperatorstobeoverloaded.(2)C++allowsnewoperatorstobecreated.(3)Anyoperatorcanbeoverloaded..(4)Howanoperatorworksonbasictypescannotbechangedbyoperatoroverloading.(5)Theassociativityofanoperatorcanbechangedbyoperatoroverloading.(6)Theprecedenceofanoperatorcannotbechangedbyoperatoroverloading.(7)Overloadedassignmentoperatorsmustbedeclaredasnon-memberfunctions.(8)Overloadedoperatormemberfunctionsforbinaryoperatorsimplicitlyusethistoobtainaccesstotheleftoperandoftheoperator.(9)Aunaryoperatorcanbeoverloadedasanon-memberfunction.(10)Abinaryoperatorcanbeoverloadedasanon-memberfunctiontakingoneargument.(11)Aconversionoperatorconvertsanobjectofoneclassintoanobjectofanotherclass.(12)The++(or-)operatorscanbeoverloadedforbothprefixandpostfixincrement(ordecrement).以下是对每个状态的标记和理由:(1)C++允许操作符重载。--真(T)理由:C++是一种面向对象的编程语言,它提供了强大的操作符重载机制,允许程序员修改已有的操作符的行为。(2)C++允许创建新的操作符。--假(F)理由:C++不允许程序员创建新的操作符。操作符是由语言本身定义和实现的,程序员只能重载已有的操作符。(3)任何操作员都可能过载。--真(T理由:在C++中,几乎所有的操作符都可以重载,包括算术操作符、比较操作符、逻辑操作符等。(4)操作符对基本类型的工作方式不能因操作符重载而改变。--假(F)理由:通过操作符重载,可以改操作符对基本类型的工作方式。例如,可以重载加法操作符\,使其能够连接两个字符串。(5)运算符的关联性可以通过运算符重载来改变。--真(T)理由:C++允许通过操作符重载来改变运算符的关联性。例如,可以通过重载\操作符来实现类似于字符串拼接的效果,将两个字符串连接在一起。(6)假(False)。操作符的重载可以改变操作符的优先级。例如,重载的操作符可以优先级高于原始操作符。(7)假(False)。过载的分配操作符可以声明为成员函数或非成员函数。通常,推荐将其声明为成员函数,以便操作符能够访问类的私有成员。(8)真(True)。二进制运算符的成员函数隐式地使用它来获取对左操作数的访问权,而右操作数作为函数的参数传递给该函数。真(True)。一元运算符可以作为非成员函数重载,特别是当一元运算符作用于类对象时,非成员函数重载提供了更灵活的选项。(10)假(F):二进制运算符一般作为成员函数或全局函数来定义,并且通常需要两个参数。(11)真(T):转换运算符可以定义将一个类的对象转换为另一个类的对象,这样可以在类型之间进行隐式转换。(12)真(T):前缀和后缀增量(或递减)运算符可以被重载,使其可以根据需要在前缀或后缀位置使用。例如,++i和i++都可以使用重载的增量运算符。2.Giventhefollowingprogram.Defineoverloadingoperators=,+and++andwriteouttheoutputoftheprogram.略。3.WriteaprogramthatdefinesaDateclasstoimplementthefollowingoperations:(1)Printadate;(2)Incrementthedatebyonemonth;(3)Comparetwodatesbyrelationoperators=,<=,and!=;(4)Overloadinsertion(>>)andextraction(<<)operatorsforeasyinputandoutput.(TheDateclassrequirestheusertoinput/outputadateintheform:dd/mm/yy)```cpp#include<iostream>#include<sstream>classDate{private:intday;intmonth;intyear;public:Date(intd,intm,inty):day(d),month(m),year(y){}voidprintDate(){std::cout<<day<<\<<month<<\<<year<<std::endl;}voidaddOneMonth(){month++;if(month>12){month=1;year++;}}booloperator==(constDate&other)const{return(day==other.day&&month==other.month&&year==other.year);}booloperator<=(constDate&other)const{return(year<other.year||(year==other.year&&month<other.month)||(year==other.year&&month==other.month&&day<=other.day));}booloperator!=(constDate&other)const{return!(*this==other);}friendstd::istream&operator>>(std::istream&is,Date&date){std::stringinput;std::getline(is,input);std::stringstreamss(input);std::stringtoken;std::getline(ss,token,'/');date.day=std::stoi(token);std::getline(ss,token,'/');date.month=std::stoi(token);std::getline(ss,token);date.year=std::stoi(token);returnis;}friendstd::ostream&operator<<(std::ostream&os,constDate&date){os<<date.day<<\<<date.month<<\<<date.year;returnos;}};intmain(){Datedate(1,1,2022);date.printDate();date.addOneMonth();date.printDate();DateanotherDate(31,12,2021);if(date==anotherDate){std::cout<<\Datesareequal.\<<std::endl;}elseif(date<=anotherDate){std::cout<<\Dateislessthanorequaltoanotherdate.\<<std::endl;}else{std::cout<<\Dateisgreaterthananotherdate.\<<std::endl;}std::cout<<\Enteradate(dd/mm/yy):\std::cin>>date;std::cout<<\EnteredDate:\<<date<<std::endl;return0;}```这个程序创建了一个名为Date的类,用于处理日期。它具有打印日期、增加一个月、比较两个日期和输入/输出日期的功能。在主函数中,我们创建一个Date对象并使用printDate方法打印日期。然后,我们使用addOneMonth方法将日期增加一个月,并再次打印日期。接下来,我们创建另一个Date对象,并使用关系运算符来比较两个日期。最后,我们使用重载的输入和输出操作符来输入和输出日期。请注意,此程序假设用户输入的日期格式符合\dd/mm/yy\的要求,比较操作符(==、<=和!=)和输入/输出操作符(<<和>>)都被重载为类的成员方法或友元函数。4.Giventhefollowingprogram:WriteoutthedefinitionsofallmemberfunctionsandafriendfunctionwithintheCVectorclassandtesttheminthemainfunction.略。5.GiventhedeclarationoftheIntegerclass:(1)WritethedefinitionofallmemberfunctionsoutsidetheIntegerclass.(2)Writethemainfunctiontotestthem.略。6.DefinetheCounterclassincludingoverloadingoperator++.下面是一个示例的计数器类,包括重载了前置和后置自增运算符(++)的实现:```pythonclassCounter:def__init__(self,count=0):self.count=countdef__repr__(self):returnf\Counter(count={self.count})\defincrement(self):self.count+=1def__iadd__(self,other):ifisinstance(other,int):self.count+=otherelse:raiseTypeError(\Countercanonlybeincrementedbyaninteger.\returnselfdef__add__(self,other):ifisinstance(other,int):returnCounter(self.count+other)else:raiseTypeError(\Countercanonlybeaddedtoaninteger.\def__radd__(self,other):returnself.__add__(other)def__pos__(self):self.increment()returnselfdef__rshift__(self,other):ifisinstance(other,int):self.count=otherelse:raiseTypeError(\Countercanonlybeassignedanintegervalue.\returnself.countdef__rrshift__(self,other):returnself.__rshift__(other)#实例化计数器对象c1=Counter(5)print(c1)#Output:Counter(count=5)#前置自增运算符(++)++c1print(c1)#Output:Counter(count=6)#后置自增运算符(++)c1++print(c1)#Output:Counter(count=7)#操作符重载:+=c1+=3print(c1)#Output:Counter(count=10)#操作符重载:+c2=c1+5print(c2)#Output:Counter(count=15)#操作符重载:+=c2+=c1print(c2)#Output:Counter(count=25)#操作符重载:+c3=20+c2print(c3)#Output:Counter(count=45)#操作符重载:+++c3print(c3)#Output:Counter(count=46)#操作符重载:>>c3>>100print(c3)#Output:Counter(count=100)#操作符重载:>>=c3>>=50print(c3)#Output:50```7.WhentheC++programisrunning,itwillnotcheckwhetheranarrayisoutofboundautomatically.WriteaprogramthatcandoitbyoverloadingoperatorD.当C++程序运行时,它并不会自动检查数组是否越界。然而,你可以编写一个程序来通过重载操作符D来实现对数组的越界检查。下面是一个简单的示例程序:```cpp#include<iostream>classArray{private:int*data;intsize;public:Array(intn){size=n;data=newint[size];}~Array(){delete[]data;}int&operator[](intindex){if(index<0||index>=size){std::cout<<\Error:Arrayindexoutofbounds\<<std::endl;exit(1);}returndata[index];}};intmain(){Arrayarr(5);//设置元素值arr[0]=1;arr[1]=2;arr[2]=3;arr[3]=4;arr[4]=5;//访问数组元素for(inti=0;i<6;i++){std::cout<<\arr[\<<i<<\=\<<arr[i]<<std::endl;}return0;}```在这个例子中,我们创建了一个名为Array的类,它封装了一个动态分配的整型数组。通过重载操作符[],我们可以使用像`arr[i]`这样的语法来访问数组元素。在重载的操作符函数中,我们首先检查索引是否越界,如果越界,我们输出错误信息并终止程序。如果索引没有越界,则返回对应的数组元素的引用。在主函数中,我们创建了一个大小为5的Array对象,并设置了一些元素的值。然后,我们使用一个循环尝试访问6个元素,其中最后一个是越界的。当程序尝试访问越界的元素时,它会显示错误信息并退出。8.ModifytheTimeDemoclasstoimplementtheinputandoutputofthetime.Overloadingoperator>>toinputtimefromtheuser.Overloadingoperator<<tooutputthetimetoconsole.```pythonclassTime:def__init__(self,hour=0,minute=0,second=0):self.hour=hourself.minute=minuteself.second=second#重载>>操作符用于从用户输入时间def__rshift__(self,other):time_str=input(\请输入时间(格式:hh:mm:ss):\time_list=time_str.split(\\self.hour=int(time_list[0])self.minute=int(time_list[1])self.second=int(time_list[2])#重载<<操作符用于输出时间到控制台def__lshift__(self,other):print(f\现在的时间是:{self.hour:02d}:{self.minute:02d}:{self.second:02d}\```使用这个修改后的类,你可以这样输入和输出时间:```pythontime=Time()time>>None#输入时间time<<None#输出时间```这个类中,我们使用了`__rshift__`方法重载了`>>`操作符,以实现从用户输入时间。然后使用`__lshift__`方法重载了`<<`操作符,以实现将时间输出到控制台。9.DesignaPercentclassthatrepresentsthepercentageof10%,80%andetc.Overloadoperators<<and>>toimplementtheoutputandinputofPercentobjects;Overloadoperators==and<tocomparetherelationshipoftwoPercentobjects.```cpp#include<iostream>classPercentage{public:Percentage(intvalue):m_value(value){}friendstd::ostream&operator<<(std::ostream&os,constPercentage&percentage);friendstd::istream&operator>>(std::istream&is,Percentage&percentage);friendbooloperator==(constPercentage&p1,constPercentage&p2);friendbooloperator<(constPercentage
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 婴儿湿疹的预防与治疗课件
- 2026及未来5年疝气带项目可行性研究报告
- 双侧滑动性腹股沟斜疝的护理
- 高二物理期中复习
- 2026年度河北省禁毒知识应知应会考试题库及答案
- 2026年度广西崇左市专业技术人员继续教育公需科目试卷及答案
- 2026年度管理干部综合能力培训发展规划
- 《中药指纹图谱》课件
- 马鞍山市机关事业单位职工健步走竞赛软件培训
- 《你的形象价值百万》课件
- 2025年及未来5年市场数据中国机械密封行业发展监测及投资战略规划研究报告
- 乡土文学课件
- 鼠疫应急处置培训课件
- T∕CSTM 00181-2020 化学试剂 六水合氯化锶
- 基于Spring Boot的线上教育平台的设计与实现
- 中国石化保密管理制度
- 犊牛饲养管理要点与技术规范
- 病区免陪照护服务的规范化管理与实践
- 2024年秋季新苏教版一年级上册数学教学课件 第二单元 第4课时 连加、连减、加减混合
- 部编版八年级语文上册第7课《回忆我的母亲》精美课件
- 一年级下册《劳动》全册教学设计教案
评论
0/150
提交评论