C++运算符重载

下面我来举个C++基本的运算符重载的例子:

Operator.h头文件:

#pragma once
#include<iostream>
using namespace std;
class Operator
{
public:
	Operator(double ,double);
	~Operator();
	Operator &operator+(Operator &);
	Operator operator-(Operator t);
	Operator operator++();
	Operator operator++(int);
    friend Operator operator--(Operator &);
	friend Operator operator--(Operator &,int);
	Operator operator*(Operator t);
	Operator operator/(Operator t);
	Operator &operator=(Operator &);
	operator double();
	friend ostream &operator <<(ostream &output, Operator &);
	friend istream &operator>>(istream &input, Operator &);
	void show();
private:
	double x, y;
};

operator.cpp文件:

#include"operator.h"
Operator::Operator(double a=0, double b=0) { x = a, y = b;};
Operator::~Operator() {};

Operator &Operator::operator+(Operator &obj)
{
	x = x + obj.x;
	y = y + obj.y;
	return *this;
};
Operator Operator::operator-(Operator t)
{
	Operator temp;
	temp.x = x - t.x;  temp.y = y - t.y;
	return Operator(temp.x,temp.y);
};
Operator Operator::operator++() { x++, y++; return *this; };
Operator Operator::operator++(int)
{
	Operator temp;
	temp.x = x++;
	temp.y = y++;
	return temp;
};
Operator operator--(Operator &a)
{
	a.x--, a.y--;
	return a;
};
Operator operator--(Operator &a, int)
{
	int xx = a.x--;
	int yy = a.y--;
	return Operator(xx,yy);
};
Operator Operator::operator*(Operator t)
{	
	Operator temp;
	temp.x = (x*t.x - y*t.y);
	temp.y = (y*t.x + x*t.y);
	return temp;
};
Operator Operator::operator/(Operator t)
{
	//(ac+bd)/(c2+d2) +((bc-ad)/(c2+d2))i
	Operator temp;
	temp.x = (x*t.x + y*t.y)/(t.x*t.x + t.y*t.y);
	temp.y = (y*t.x - x*t.y)/(t.x*t.x + t.y*t.y);
	return temp;
};
Operator &Operator::operator=(Operator &obj)
{
	x = obj.x; y = obj.y;
	return *this;
};
Operator::operator double()
{
	return  double(x)/ double(y);
};
 ostream &operator <<(ostream &output, Operator &x)
 {
	 output << "("<<x.x << "," << x.y<<")";     return output;
	 output << endl;
	 return output;
 };
 istream &operator>>(istream &input, Operator &x)
 {
	 input >> x.x>>x.y;
	 return  input;
};
void Operator::show() { cout <<"("<< x << "," << y << ")"<<endl;};

mainoperator文件:

#include"operator.h";
void mainoperator()
{
	Operator a(1, 2), b(2, 1), c(0, 0),d(0,0);
	c = a++; c.show();
	c = ++a; c.show();
	c = a--; c.show();
	c = --a; c.show();
	c = b-a; c.show();
	c = a+b; c.show();
	cout << a << " + " << b << " = " << c << endl;
	cin >> d;
	d.show();
	c = a*b; c.show();//(ac-bd)+(bc+ad)i
	c = a / b;
	c.show();//(ac+bd)/(c2+d2) +((bc-ad)/(c2+d2))i
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值