一、实验目的1.理解静态联编和动态联编的概念;2.理解掌握成员函数方式运算符重载;3.理解掌握友元函数方式运算符重载;4.理解掌握++、--、=运算符的重载。二、实验内容2.1练习(一):1.理解下面的程序,并在VC++6.0下运行查看结果,回答程序后面的问题。#include "iostream.h"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;}};void main(){CComplex obj1(100,30);CComplex obj2(20, 30);CComplex obj;obj = obj1+obj2; ------------------------------------------------------------------②cout << obj.real <<endl;cout << obj.imag << endl;}问题一:①处的运算符重载,为什么该函数的返回值要设计成CComplex类型?问题二:②处的运算符重载函数调用就相当于“obj=operator+(obj1,obj2);”,但是为什么CComplex类中的运算符重载函数只设计了一个参数?2.理解下面的程序,并在VC++6.0下运行查看结果,回答程序后面的问题。#include "iostream.h"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<<real<<"+"<<imag<<"i"<<endl;}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=";obj1.print();cout<<"obj2=";obj2.print();CComplex obj3 = obj1 + obj2;cout<<"befor++, obj3=";obj3.print();++obj3;cout<<"after++, obj3=";obj3.print();--obj3;cout<<"after--, obj3=";obj3.print();CComplex obj4 = ++obj3;cout<<"obj4=";obj4.print();}问题一:以上程序中的三个运算符重载都有错误,试改正过来,并分析该程序的输出结果。2.2练习(二):1.把2.1中第一道题的程序改造成采取友元函数重载方式来实现“+”运算符,并采取友元函数重载方式增加前置和后置“++”以及“--”运算符重载,并设计主函数来验证重载运算符的用法。
目前暂无任何回答
- 0 回答
- 0 关注
- 3147 浏览
添加回答
举报
0/150
提交
取消