实验七-运算符重载参考答案

  • 格式:docx
  • 大小:19.27 KB
  • 文档页数:8

下载文档原格式

  / 8
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验七多态性—函数与运算符重载7.1 实验目的

1.理解掌握成员函数方式运算符重载;

2.理解掌握友元函数方式运算符重载;

3.理解掌握++、--运算符的重载。

7.2 实验内容

7.2.1程序阅读

1.理解下面的程序,并运行查看结果,回答程序后面的问题。

#include

using namespace std;

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;

}

};

int main()

{

CComplex obj1(100,30);

CComplex obj2(20, 30);

CComplex obj;

obj = obj1+obj2; //------------------------------------------------------------------②

cout << obj.real <

cout << obj.imag << endl;

return 0;

}

问题一:①处的运算符重载,为什么该函数的返回值要设计成CComplex类型?

答:因为在函数中return obj2,obj2是CComplex类型,所以函数返回值要与return返回的类型相同,即设计成CComplex类型。

问题二:②处的运算符重载函数调用就相当于“obj=operator+(obj1,obj2);”,但是为什么CComplex类中的运算符重载函数只设计了一个参数?

答:因为成员函数经编译后会产生this指针,this指针会指向调用该函数的obj1对象,该obj1对象就是就相当于函数的第一个参数。因此可以在函数参数列表中只设计一个参数。问题三:上述程序设计合理吗?为什么?

答:不合理,因为它所实现的功能是obj2-obj1,而重载运算符的名字为“+”,这使用起来非常不直观,会让人以为这实现的功能是obj1+obj2。

2.理解下面的程序,并运行查看结果,回答程序后面的问题。

#include

using namespace std;

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;

++obj.imag ;

return obj;

}

void print()

{

cout<

}

private:

float real;

float imag;

};

CComplex &operator--(CComplex &x) //重载前置自减运算符

{

--x.real;

--x.imag;

return x;

}

int 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<<"before++, obj3=";

obj3.print();

++obj3;

cout<<"after++, obj3=";

obj3.print();

--obj3;

cout<<"after--, obj3=";

obj3.print();

CComplex obj4 = ++obj3;

cout<<"obj4=";

obj4.print();

return 0;

}

问题一:以上程序中的三个运算符重载都有错误,试改正过来,使程序输出正确结果。