全局函数实现
#include <iostream>
using namespace std;
class Pr
{
friend const Pr operator*(const Pr &L,const Pr &R);
friend bool operator<=(const Pr &L,const Pr &R);
friend Pr & operator*=( Pr &L, const Pr &R);
private:
int a;
int b;
public:
Pr(){};
Pr(int a,int b):a(a),b(b){}
void show()
{
cout << " a=" << a << endl;
cout << " b=" << b << endl;
}
};
const Pr operator*(const Pr &L,const Pr &R)
{
Pr temp;
temp.a=L.a*R.a;
temp.b=L.b*R.b;
}
bool operator<=(const Pr &L,const Pr &R)
{
if(L.a<=R.a && L.b<=R.b)
{
return true;
}
else
{
return false;
}
}
Pr & operator*=( Pr &L, const Pr &R)
{
L.a*=R.a;
L.b*=R.b;
return L;
}
int main()
{
Pr p1();
Pr p2(2,4);
Pr p3(4,2);
Pr p4=p3*p2;
p4.show();
if(p3 <= p4)
{
cout << "p3>p2" << endl;
}
else
{
cout << "p3<p2" << endl;
}
p2*=p3;
p2.show();
return 0;
}
成员函数实现
#include <iostream>
using namespace std;
class Pr
{
private:
int a;
int b;
public:
Pr(){}
Pr(int a,int b):a(a),b(b){}
const Pr operator*(const Pr &R) const
{
Pr temp;
temp.a=a*R.a;
temp.b=b*R.b;
return temp;
}
bool operator<(const Pr &R)
{
if(a<R.a && b<R.b)
{
cout << "小于" << endl;
}
else
{
cout << "大于" << endl;
}
}
Pr & operator*=(const Pr &R)
{
a*=R.a;
b*=R.b;
return *this;
}
void show()
{
cout << "a= " << a << endl;
cout << "b= " << b << endl;
}
};
int main()
{
Pr p1(4,3);
Pr p2(3,4);
Pr p3=p1 * p2;
p3<p2;
p1*=p2;
p1.show();
p3.show();
return 0;
}