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)





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值