下面我来举个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
}