C++學習筆記之運算符重載

operator <運算符>
例1 :複數的+、-、=運算 
// 文件1:complex1.h--複數類的定義
#ifndef COMPLEX1_H
#define COMPLEX1_H
class Complex {
public:
	Complex(double = 0.0, double = 0.0);     
	Complex operator+(const Complex&) const;     
	Complex operator-(const Complex&) const; 
	Complex& operator=(const Complex&);      
	void print() const;                      
private:
	double real;       // real part
	double imaginary;  // imaginary part
};
#endif
//文件2:complex1.cpp--複數類的成員函數定義
#include <iostream.h>
#include "complex1.h"
Complex::Complex(double r, double i)
{  real = r;
imaginary = i;
}
Complex Complex::operator+(const Complex &operand2) const
{
	Complex sum;
	sum.real = real + operand2.real;
	sum.imaginary=imaginary + operand2.imaginary;
	return sum;
}
Complex Complex::operator-(const Complex &operand2) const
{
	Complex diff;
	diff.real = real - operand2.real;
	diff.imaginary=imaginary - operand2.imaginary;
	return diff;
}
Complex& Complex::operator=(const Complex &right)
{
	real = right.real;
	imaginary = right.imaginary;
	return *this;   // enables concatenation
} 
void Complex::print() const
{ cout<<'('<<real<< ", " << imaginary << ')'; }
//文件3: FIG13_1.cpp--主函數定義
#include <iostream.h>
#include "complex1.h"
main()
{
	Complex x, y(4.3, 8.2), z(3.3, 1.1);
	cout << "x: ";
	x.print();
	cout << "\ny: ";
	y.print();
	cout << "\nz: ";
	z.print();
	x = y + z;
	cout << "\n\nx = y + z:\n";   
	x.print();
	cout << " = ";
	y.print();
	cout << " + ";
	z.print();
	x = y - z;
	cout << "\n\nx = y - z:\n";
	x.print();
	cout << " = ";
	y.print();
	cout << " - ";
	z.print();
	cout << '\n';
	return 0;
}
程序執行結果:
x: (0, 0)
y: (4.3, 8.2)
z: (3.3, 1.1)
x = y + z:
(7.6, 9.3) = (4.3, 8.2) + (3.3, 1.1)
x = y - z:
(1, 7.1) = (4.3, 8.2) - (3.3, 1.1)





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章