C++实验报告十二Word文件下载.docx
《C++实验报告十二Word文件下载.docx》由会员分享,可在线阅读,更多相关《C++实验报告十二Word文件下载.docx(7页珍藏版)》请在冰豆网上搜索。
教师签名:
年月日
成绩评定
备注
一、实验目的
1.理解运行时的多态性和编译时的多态性
2.掌握运算符重载的两种方法
二、实验内容
1.验证例6.2,根据课本上的程序分析,验证分析结果
2.验证例6.4
3.理解几个常用的运算符重载实例
三、实验结果及其结果分析
例6.2
(1)源程序:
#include<
iostream.h>
string.h>
classString
{
charname[256];
public:
String(char*str)
{
strcpy(name,str);
}
String(){}
~String(){}
Stringoperator+(constString&
);
voiddisplay()
cout<
<
"
Thestringis:
name<
endl;
};
staticchar*str;
StringString:
:
operator+(constString&
a)
strcpy(str,name);
strcat(str,a.name);
returnString(str);
}
voidmain()
str=newchar[256];
Stringdemo1("
VisualC++"
Stringdemo2("
6.0"
demo1.display();
demo2.display();
Stringdemo3=demo1+demo2;
demo3.display();
Stringdemo4=demo3+"
Programming."
;
demo4.display();
deletestr;
(2)实验结果:
(3)程序分析:
考虑上述表达式:
demo3+“Programming.”
如果将此运算符重载为成员函数,则上述表达式被解释为:
demo3.operator+(“Programming.”)
然后编译程序将调用String类的构造函数将“Programming.”转换为String类的对象,最后被解释为:
demo3.operator+(String(“Programming.”))
匹配如下的成员函数得最后结果:
Stringoperator+(constString&
operator+函数体中的最后一条语句returnString(str);
执行时不调用拷贝构造函数。
但是若此函数定义改为:
operator+(constString&
a)
Strings;
strcpy(s.name,name);
strcat(s.name,a.name);
returns;
则返回s时要调用拷贝构造函数。
main()函数中的语句Stringdemo3=demo1+demo2;
不调用对赋值号的重载函数,也不调用拷贝构造函数创建demo3,这只是初始化语句,如果把该语句改为:
stringdemo3;
demo3=demo1+demo2;
这时会调用对=的重载函数。
例6.4
friendStringoperator+(constString&
constString&
a,constString&
b)
strcpy(str,a.name);
strcat(str,b.name);
Stringdemo5="
+demo4;
demo5.display();
(3)程序分析:
如果将此运算符重载为友元函数,则上述表达式被解释为:
operator+(demo3+“Programming.”)
operator+(demo3,String(“Programming.”))
匹配成员函数:
friendStringoperator+(constString&
再考虑上述表达式:
“Programming.”+demo4
如果将此运算符重载为成员函数,则此表达式被解释为:
“Programming.”.operator+(demo4)
但“Programming.”不是一个对象,不能调用成员函数,所以编译系统将报告如下的错误:
errorC2677:
binary‘+’:
noglobaloperatordefinedwhichtakestype‘classString’(orthereisnoacceptableconversion)
operator+(“Programming.”,demo4)
operator+(String(“Programming.”),demo4)
最后匹配成员函数:
四、实验收获与体会
本次实验主要练习了跟运算符重载有关的程序的调试编译。
通过本次实验,我更加深入地理解了运行时的多态性和编译时的多态性的概念,也能够正确掌握运算符重载的两种方法。
运算符重载的实质就是函数重载,重载运算符可以通过成员函数或者友元函数。
在实现过程中,首先把指定的运算符表达式转换为对运算符函数的调用,运算对象转化为运算符函数的实参,然后根据实参的类型确定需要调用的函数,这个过程是在编译过程中完成的。