实验07. 多态性-函数与运算符重载
7.1实验目的
1、 理解动态联编和动态联编的概念; 2、 理解掌握成员函数方式运算符重载; 3、 理解掌握友元函数方式运算符重载; 4、 理解掌握++、--、=运算符的重载;
7.2实验内容 7.2.1程序阅读与调试
1.理解下面的程序,并在Code::Blocks下运行查看结果,回答程序后面的问题。
01. #include
06. public: { CComplex() real = 0; imag = 0; } { CComplex(int x, int y) real = x; imag = y; } int real; int imag; CComplex operator + (CComplex obj1) //----① { return obj2; CComplex obj2(real + obj1.real, imag + obj1.imag); } 1
26. }; 27. 28. int main() 29. { 30. 31. 32. 33. 34. 35. 36. 37. } CComplex obj1(100,30); CComplex obj2(20, 30); CComplex obj; obj = obj1 + obj2; //----② cout << obj.real < 问题1:①处的运算符重载,为什么该函数的返回值要设计成CComplex类 型 问题2:②处的运算符重载函数调用就相当于“obj=operator+(obj1,obj2);”, 但是为什么CComplex类中的运算符重载函数只设计了一个参数。 问题3:本程序的执行结果是什么。 ——请将上述问题的解答填写在实验报告对应题号下面。 2.理解下面的程序,并在Code::Blocks下运行查看结果,回答程序后面的问题。 01. #include 06. 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; } 2 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 33. 34. 36. { } { } CComplex &operator++(CComplex &obj) obj.real += 1; obj.imag += 1; return obj; void print() cout << real << \ << imag << \ << endl; 32. private: float real; float imag; 35. }; 37. CComplex &operator--(CComplex &x) 38. { 39. 40. 41. 43. 42. } x.real -= 1; x.imag -= 1; return x; 44. int main() 45. { 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. } CComplex obj1(2.1, 3.2); CComplex obj2(3.6, 2.5); cout << \; obj1.print(); cout << \; obj2.print(); CComplex obj3 = obj1 + obj2; cout << \; ++obj3; --obj3; cout << \; obj3.print(); obj3.print(); cout << \; obj3.print(); CComplex obj4 = ++obj3; cout << \; obj4.print(); return 0; 问题1:以上程序中的三个运算符重载都有错误,试改正过来,并分析该程 序的输出结果? ——请将上述问题的解答填写在实验报告对应题号下面 3 7.2.2程序设计 1.对7.2.1中的第2个程序,如果要实现后缀的--,即在主函数中添加以下语句: CComplex obj5 = obj3--; cout << \cout << \后输出: postfix after , obj5=obj3--; obj5 = 6.7 + 6.7i postfix after , obj5=obj3--; obj3 = 5.7 + 5.7i 应该如何扩展程序。该程序命名为exp07_p1_1.cpp。 7.3思考题 1、定义CPoint类,有两个成员变量:横坐标(x)和纵坐标(y),对CPoint类重载“++”(自增运算符)、“--”(自减运算符),实现对坐标值的改变。(每个函数均采用友元和成员函数实现) 4 百度搜索“77cn”或“免费范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,免费范文网,提供经典小说综合文库实验07_多态性_函数与运算符重载在线全文阅读。
相关推荐: