C++面向对象程序设计实验指导书 实验六
6.2.2 程序设计
1.建立普通的基类building,用来存储一座楼房的层数、房间数以及它的总平方数。建立派生类house,继承building,并存储卧室与浴室的数量,另外,建立派生类office,继承building,并存储灭火器与电话的数目。设计一主函数来测试以上类的用法。
6.3思考题
1.按照下图的类层次结构编写程序,定义属于score的对c1以及类teacher的对象t1,分别输入个数据成员的值后再显示出这些数据。
personnameidstudaddrtelteacherdegreedepstudentoldsnomathengscore
22
C++面向对象程序设计实验指导书 实验七
实验七 多态性—函数与运算符重载
7.1 实验目的
1.理解动态联编和动态联编的概念; 2.理解掌握成员函数方式运算符重载; 3.理解掌握友元函数方式运算符重载; 4.理解掌握++、--、=运算符的重载。
7.2 实验内容 7.2.1程序阅读
1.理解下面的程序,并在VC++6.0下运行查看结果,回答程序后面的问题。
#include \
class CComplex {
public:
CComplex() { real = 0; imag = 0; }
CComplex(int x,int y) { real = x; imag = y; }
int real; int imag;
CComplex operator + (CComplex obj1)-----------------------------------------------① { CComplex obj2(real + obj1.real, imag + obj1.imag); return obj2; } };
23
C++面向对象程序设计实验指导书 实验七
void main() {
CComplex obj1(100,30); CComplex obj2(20, 30); CComplex obj;
obj = obj1+obj2; ------------------------------------------------------------------② cout << obj.real < 问题一:①处的运算符重载,为什么该函数的返回值要设计成CComplex类型? 问题二:②处的运算符重载函数调用就相当于“obj=operator+(obj1,obj2);”,但是为什么CComplex类中的运算符重载函数只设计了一个参数? 2.理解下面的程序,并在VC++6.0下运行查看结果,回答程序后面的问题。 #include \ class CComplex { public: CComplex() { real = 0.0; imag = 0.0; } CComplex(float x, float y) { real = x; imag = y; } CComplex operator + (CComplex &obj1, CComplex &obj2) { CComplex obj3(obj1.real + obj2.real, obj1.imag + obj2.imag); return obj3; } CComplex &operator++(CComplex &obj) { obj.real += 1; obj.imag +=1; return obj; } void print() { cout< 24 C++面向对象程序设计实验指导书 实验七 private: float real; float imag; }; CComplex &operator--(CComplex &x) { x.real -= 1; x.imag -= 1; return x; } void main() { CComplex obj1(2.1,3.2); CComplex obj2(3.6,2.5); cout<<\; obj1.print(); cout<<\; obj2.print(); CComplex obj3 = obj1 + obj2; cout<<\; obj3.print(); ++obj3; cout<<\; obj3.print(); --obj3; cout<<\; obj3.print(); CComplex obj4 = ++obj3; cout<<\; obj4.print(); } 问题一:以上程序中的三个运算符重载都有错误,试改正过来,并分析该程序的输出结果。 7.2.2 程序设计 1.把7.2.1中第一道题的程序改造成采取友元函数重载方式来实现“+”运算符,并采取友元函数重载方式增加前置和后置“++”以及“--”运算符重载,并设计主函数来验证重载运算符的用法。 25 C++面向对象程序设计实验指导书 实验七 7.3思考题 1.定义CPoint类,有两个成员变量:横坐标(x)和纵坐标(y),对CPoint类重载“++”(自增运算符)、“--”(自减运算符),实现对坐标值的改变。(每个函数均采用友元禾成员函数实现) 26 百度搜索“77cn”或“免费范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,免费范文网,提供经典小说综合文库C++面向对象程序设计实验指导书(6)在线全文阅读。
相关推荐: