NO.1 操作符重载实现

来源:互联网 发布:无尽战区mac可以玩吗 编辑:程序博客网 时间:2024/05/20 21:21

   今天写了一个利用操作符重载来实现复数的一些运算的程序,写完挺快的。可最后编译时,出现了很多错误,调试了一会,最好程序成功运行了。这次调试也明白了一些东西;

1 友元函数 不能有限定词 如我刚才加的const,友元函数与成员访问符号无关,也就是说他可以放在类的任何位置。2在重载>>时,friend bool operator >>(istream &is,Complex &temp),我开始写成了friend bool operator >>(istream &is,const Complex &temp)(我是抄了上面的ostream,),这等于把这个temp 声明为只读,之后当然就不能输入数据给类了。3当文件包含其他文件时,注意头文件的重复包含.

complex0.h

#ifndef COMPLEX0_H_#define COMPLEX0_H_#include <iostream>#include <stdbool.h>using namespace std;class Complex{private:float x;float y;public:Complex (float x,float y);Complex ();~Complex ();Complex operator + (const Complex &temp) const;Complex operator - (const Complex &temp) const;Complex operator * (const Complex &temp) const;friend Complex operator * (const float temp_1,const Complex &temp);friend ostream & operator << (ostream &os,const Complex &temp);friend bool operator >> (istream &is,Complex &temp);};#endif

complex0.cpp

#include "complex0.h"Complex::Complex(){}Complex::Complex(float x,float y){this->x = x;this->y = y;}Complex::~Complex(){}//reload operator + Complex Complex::operator + (const Complex &temp) const{Complex ans;ans.x = x + temp.x;ans.y = y + temp.y;return ans;}//reload operator -Complex Complex::operator - (const Complex &temp) const{Complex ans;ans.x = x - temp.x;ans.y = y - temp.y;return ans;}//reload *Complex Complex::operator * (const Complex &temp) const{Complex ans;ans.x = x * temp.x;ans.y = y * temp.y;return ans;}//friend function :reload operator *Complex operator * (const float temp_1,const Complex &temp) {Complex ans;ans.x = temp_1 * temp.x;ans.y = temp_1 * temp.y;return ans;}//friend reload operator <<ostream & operator << (ostream &os,const Complex &temp) {os <<'(' << temp.x<<'+'<<temp.y<<'i'<<')'<<endl;return os;}//friend reload operator >>bool operator >> (istream &is, Complex &temp) {bool checknu = is.good();//check the cinis >> temp.x>>temp.y;if(checknu == false)//if false return falsereturn false;return true;}

test.cpp

#include "complex0.h"using namespace std;int main (void){Complex a (3,4);Complex c;cout <<"Enter a complex number (q to quit):";while (cin >> c){cout << "c is "<< c <<endl;cout << "a + c is " <<a + c <<endl;cout << "a - c is " <<a - c <<endl;cout << "a * c is "<<a * c <<endl;cout << "2 * c is " <<2 * c <<endl;cout << "Enter a complex number(q to quit):"; }cout <<"Done!\n";return 0;}