NO.1 操作符重載實現

   今天寫了一個利用操作符重載來實現複數的一些運算的程序,寫完挺快的。可最後編譯時,出現了很多錯誤,調試了一會,最好程序成功運行了。這次調試也明白了一些東西;

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 cin
	is >> temp.x>>temp.y;
	if(checknu == false)	//if false return false
		return 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;
}





發佈了19 篇原創文章 · 獲贊 16 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章