c++运算符重载

一、加+,减-,乘*,除/ 的运算符重载

Rational operator*(const Rational &x) const{
return Rational(x.a * this->a);
}
在这里只写乘法的,加减除的写法类似

二、<<输出,>>输入的运算符重载
        friend ostream& operator<<(ostream &out, Rational x){
out <<x.a;
return out;
}
friend istream& operator>>(istream &in, Rational &x){
in >> x.a;
return in;
}

三、单目运算符 ++
(1)前置++  如++a的写法
        Rational &operator++(){
a++;
return *this;
}
(2)后置++  如a++的写法
        Rational operator++(int){
Rational t=*this;
++(*this);
return t;
}
四、判断==,自加+=,自减等
(1)判断对象是否相等
        bool operator==(const Rational &x)const{
if (x.a == this->a)
return true;
else
return false;
}
(2)+=运算符重载
        Rational operator +=(const Rational &x){
return Rational(this->a+=x.a);
}


以下是源代码












#include<iostream>
using namespace std;

class Rational
{
public:
Rational(int a=0):a(a){}
~Rational(){}
void show(){
cout << a;
}
Rational multiply(const Rational x) const{
return Rational(this->a*x.a);
}
friend Rational pluss(const Rational &x,const Rational &y) {
return Rational(y.a + x.a);
}
Rational operator*(const Rational &x) const{
return Rational(x.a * this->a);
}
friend Rational operator+(const Rational &x,const Rational &y){
return Rational(x.a + y.a);
}
friend ostream& operator<<(ostream &out, Rational x){
out <<x.a;
return out;
}
friend istream& operator>>(istream &in, Rational &x){
in >> x.a;
return in;
}
Rational &operator++(){
a++;
return *this;
}
Rational operator++(int){
Rational t=*this;
++(*this);
return t;
}
bool operator==(const Rational &x)const{
if (x.a == this->a)
return true;
else
return false;
}
Rational operator +=(const Rational &x){
return Rational(this->a+=x.a);
}
private:
int a;
};
int main(){
int a, b;
while (true){
cout << "******************************" << endl;
Rational x, y, c;
cout << "用operator重载输入" << endl;
cin >> x >> y;
cout << "用multiply成员函数计算乘法" << endl;
cout << "a*b=";
c = x.multiply(y);
c.show();
cout << endl;
cout << "用友元plus成员函数计算乘法" << endl;
cout << "a+b=";
c = pluss(x,y);
c.show();
cout << endl;
cout << "用operator运算符重载计算乘法" << endl;
cout << "a*b=";
c = x*y;
c.show();
cout << endl;
cout << "用友元operator运算符重载计算加法" << endl;
cout << "a+b=";
c = x + y;
c.show();
cout << endl;
cout << "用operator运算符重载输出流" << endl;
cout << "a+b=";
c = x + y;
cout << c<<endl;




}
return 0;
}

你可能感兴趣的:(C++)