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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值