问题及代码:
/* *Copyright (c) 2016,烟台大学计算机学院 *All rights reserved. *文件名称:zwj.cpp *作 者:张伟晶 *完成日期:2016年5月12日 *版 本 号:v1.0 * *问题描述:用类的友元函数完成运算符重载,定义一个完整的类,使之能与double型想加减乘除 *输入描述: *程序输出: */ #include<iostream> using namespace std; class Complex { public: Complex(){real=0;imag=0;} Complex(double r,double i){real=r; imag=i;} friend Complex operator+(const Complex &c1,const Complex &c2); friend Complex operator-(const Complex &c1,const Complex &c2); friend Complex operator*(const Complex &c1,const Complex &c2); friend Complex operator/(const Complex &c1,const Complex &c2); void display(); // 扩充功能1 friend Complex operator+(Complex c1,double d); friend Complex operator-(Complex c1,double d); friend Complex operator*(Complex c1,double d); friend Complex operator/(Complex c1,double d); //扩充2 friend Complex operator+(double d,Complex c1); friend Complex operator-(double d,Complex c1); friend Complex operator*(double d,Complex c1); friend Complex operator/(double d,Complex c1); private: double real; double imag; }; //扩充2 Complex operator+(double d,Complex c1) { return Complex(d+c1.real,c1.imag); } Complex operator-(double d,Complex c1) { return Complex(d-c1.real,c1.imag); } Complex operator*(double d,Complex c1) { return Complex(d*c1.real,c1.imag); } Complex operator/(double d,Complex c1) { return Complex(d/c1.real,c1.imag); } //扩充功能 Complex operator+(Complex c1,double d) { return Complex(c1.real+d,c1.imag); } Complex operator-(Complex c1,double d) { return Complex(c1.real-d,c1.imag); } Complex operator*(Complex c1,double d) { return Complex(c1.real*d,c1.imag); } Complex operator/(Complex c1,double d) { return Complex(c1.real/d,c1.imag); } //下面定义成员函数 //友元函数 Complex operator+(const Complex &c1,const Complex &c2) { return Complex(c1.real+c2.real,c1.imag+c2.imag); } Complex operator-(const Complex &c1,const Complex &c2) { return Complex(c1.real-c2.real,c1.imag-c2.imag); } Complex operator*(const Complex &c1,const Complex &c2) { return Complex(c1.real*c2.real,c1.imag*c2.imag); } Complex operator/(const Complex &c1,const Complex &c2) { return Complex(c1.real/c2.real,c1.imag/c2.imag); } void Complex::display() { cout<<"("<<real<<","<<imag<<"i)"<<endl; } //下面定义用于测试的main()函数 int main() { Complex c1(3,4),c2(5,-10),c3; cout<<"c1="; c1.display(); cout<<"c2="; c2.display(); c3=c1+c2; cout<<"c1+c2="; c3.display(); c3=c1-c2; cout<<"c1-c2="; c3.display(); c3=c1*c2; cout<<"c1*c2="; c3.display(); c3=c1/c2; cout<<"c1/c2="; c3.display(); cout<<endl; c3=c1+4; cout<<"验证1:"<<"c1+4="; c3.display(); c3=5+c1; cout<<"验证2:"<<"5+c1="; c3.display(); return 0; }
运行结果:
知识点总结:
注意!complex+double 与double+complex 不同!!!
学习心得: