作业
实现关系运算符的重载
#include <iostream>
using namespace std;
class B;
class A
{
friend const B operator%(const A &s,const A &d);
friend const B operator/(const A &s,const A &d);
friend const B operator*(const A &s,const A &d);
friend const B operator-(const A &s,const A &d);
friend const B operator+(const A &s,const A &d);
private:
int n;
int a;
public:
A(){}
A(int n,int a):n(n),a(a)
{}
void show()
{
cout << n << " " << a <<endl;
}
//成员函数实现运算符重载
//结果不被改变 右操作数不被改变 左操作数不被改变
// const A operator+(const A &s) const
// {
// A temp;
// temp.a = s.a + d.a + s.n + d.n;
// temp.n = s.a + d.a + s.n + d.n;
// return temp;
// }
bool operator<(const A &d) const
{
return (this->a + this->n) < (d.a + d.n);
}
bool operator>(const A &d) const
{
return (this->a + this->n) > (d.a + d.n);
}
bool operator==(const A &d) const
{
return (this->a + this->n) == (d.a + d.n);
}
bool operator!=(const A &d) const
{
return (this->a + this->n) != (d.a + d.n);
}
};
class B
{
friend const B operator%(const A &s,const A &d);
friend const B operator/(const A &s,const A &d);
friend const B operator*(const A &s,const A &d);
friend const B operator-(const A &s,const A &d);
friend const B operator+(const A &s,const A &d);
private:
int b;
public:
B(){}
B(int a):b(a){}
void show()
{
cout << b << endl;
}
bool operator<=(const B &a) const
{
return this->b <= a.b;
}
bool operator>=(const B &a) const
{
return this->b >= a.b;
}
bool operator!=(const B &a) const
{
return this->b != a.b;
}
};
//全局函数实现运算符重载
const B operator+(const A &s,const A &d)
{
B temp;
temp.b = s.a + d.a + s.n + d.n;
return temp;
}
const B operator-(const A &s,const A &d)
{
B temp;
temp.b = (s.a + s.n) - (d.a + d.n);
return temp;
}
const B operator*(const A &s,const A &d)
{
B temp;
temp.b = (s.a + s.n) * (d.a + d.n);
return temp;
}
const B operator/(const A &s,const A &d)
{
B temp;
temp.b = (s.a + s.n) / (d.a + d.n);
return temp;
}
const B operator%(const A &s,const A &d)
{
B temp;
temp.b = (s.a + s.n) % (d.a + d.n);
return temp;
}
/*
const bool operator<(const A &s,const A &d)
{
return (s.a + s.n) < (d.a + d.n);
}
const bool operator>(const A &s,const A &d)
{
return (s.a + s.n) > (d.a + d.n);
}
const bool operator==(const A &s,const A &d)
{
return (s.a + s.n) == (d.a + d.n);
}*/
int main()
{
int n1,n2,n3,n4,n5,n6;
cin >> n1;
cin >> n2;
cin >> n3;
cin >> n4;
cin >> n5;
cin >> n6;
A a(n1,n2);
a.show();
A b(n3,n4);
b.show();
B d(n5);
B e(n6);
B c = a+b;
c.show();
c = a-b;
c.show();
c = a*b;
c.show();
c = a/b;
c.show();
c = a%b;
c.show();
if(a<b)
{
cout << "a < b" << endl;
}
else if(a>b)
{
cout << "a > b" << endl;
}
if(a != b)
{
cout << "a != b" << endl;
}
else
{
cout << "a = b" << endl;
}
if(d <= e)
{
cout << "d <= e" << endl;
}
else if(d >= e)
{
cout << "d >= e" << endl;
}
if (d != e)
{
cout << "d != e" << endl;
}
return 0;
}
思维导图