一、实验目的和要求 1.掌握静态联编和动态联编的概念; 2.掌握成员函数方式运算符重载; 3.掌握友元函数方式运算符重载; 4.理解掌握++、--、=运算符的重载。 |
二、实验环境(软、硬件及条件) 一台安装有Visual C++ 6.0的计算机 |
三、实验步骤 1、阅读下面的程序,回答程序后面的问题。 #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; }
问题1:写出程序的运行结果 问题2:①处的运算符重载,为什么该函数的返回值要设计成CComplex类型? 问题3:②处的运算符重载函数调用就相当于“obj=operator+(obj1,obj2);”,但是为什么CComplex类中的运算符重载函数只设计了一个参数?
2、阅读下面的程序,找出其中的错误并改正。
#include "iostream.h"
class CComplex { public: CComplex() { real = 0.0; imag = 0.0; } CComplex(double x, double y) { real = x; imag = y; } CComplex operator + (CComplex &obj1) { CComplex obj3(real + obj1.real, imag + obj1.imag); return obj3; } CComplex &operator++(CComplex &obj) { obj.real += 1; obj.imag +=1; return obj; } void print() { cout<<real<<"+"<<imag<<"i"<<endl; } private: double real; double imag; };
void main() { CComplex obj1(2.1,3.2); CComplex obj2(1.3,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(); } |
四、实验中遇到的问题及解决 无 |
五、实验结果及分析 1. 问题1.运行结果: 120 60 问题2. 因为①处所运用达到是CComplex类的重载+运算符,两个CComplex相加后结果仍为CComplex. 问题3. 因为重载+运算符在程序中相当于成员函数,第一个参数由this指针隐含调用,所以只设置第二个参数。 2. #include <iostream> using namespace std; class CComplex { public:
CComplex() { real = 0.0; imag = 0.0; } CComplex(double x, double y) { real = x; imag = y; } CComplex operator + (CComplex &obj1) { CComplex obj3(real + obj1.real, imag + obj1.imag); return obj3; } CComplex & CComplex::operator++() { real += 1; imag +=1; return *this; } void print() { cout<<real<<"+"<<imag<<"i"<<endl; } private: double real; double imag; };
void main() { CComplex obj1(2.1,3.2); CComplex obj2(1.3,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(); } |