1 class person{ 2 private: 3 int age; 4 public: 5 person(int a){ 6 this->age=a; 7 } 8 inline bool operator == (const person &ps) const; 9 };
實現方式如下:
1 inline bool person::operator==(const person &ps) const 2 { 3 if (this->age==ps.age) 4 return true; 5 return false; 6 }
調用方式如下:
1 #include 2 using namespace std; 3 int main() 4 { 5 person p1(10); 6 person p2(20); 7 if(p1==p2) cout<<”the age is equal!”< return 0; 8 }
這裏,因爲operator ==是class person的一個成員函數,所以對象p1,p2都可以調用該函數,上面的if語句中,相當於p1調用函數==,把p2作爲該函數的一個參數傳遞給該函數,從而實現了兩個對象的比較。
1 class person 2 { 3 public: 4 int age; 5 public: 6 }; 7 8 bool operator==(person const &p1 ,person const & p2) 9 //滿足要求,做操作數的類型被顯示指定 10 { 11 if(p1.age==p2.age) 12 return true; 13 return false; 14 }
調用方式如下:
1 int main() 2 { 3 person rose; 4 person jack; 5 rose.age=18; 6 jack.age=23; 7 if(rose==jack) 8 cout<<"ok"< return 0; 9 }
#include <iostream>
using namespace std;
class A
{
public:
A(double _data = 0.0):data(_data){}
A& operator = (const A& rhs)
{
data = rhs.data;
return *this;
}
friend A operator + (const A& lhs,const A& rhs);
friend A operator - (const A& lhs,const A& rhs);
friend A operator * (const A& lhs,const A& rhs);
friend A operator + (const A& lhs,double rhs);
friend A operator + (double lhs,const A& rhs);
friend A operator * (const A& lhs,double rhs);
friend A operator * (double lhs,const A& rhs);
friend A operator - (const A& lhs,double rhs);
friend A operator - (double lhs,const A& rhs);
friend ostream& operator << (ostream& fout,A& a);
// A& operator += (const A& rhs);
// A& operator -= (const A& rhs);
// A& operator *= (const A& rhs);
private:
double data;
};
A operator + (const A& lhs,const A& rhs)
{
A res(0);
res.data = lhs.data + rhs.data;
return res;
}
A operator - (const A& lhs,const A& rhs)
{
A res(0);
res.data = lhs.data - rhs.data;
return res;
}
A operator * (const A& lhs,const A& rhs)
{
A res(0);
res.data = lhs.data * rhs.data;
return res;
}
A operator + (const A& lhs,double rhs)
{
A res(0);
res.data = lhs.data + rhs;
return res;
}
A operator + (double lhs,const A& rhs)
{
A res(0);
res.data = lhs + rhs.data;
return res;
}
A operator * (const A& lhs,double rhs)
{
A res(0);
res.data = lhs.data * rhs;
return res;
}
A operator * (double lhs,const A& rhs)
{
A res(0);
res.data = lhs * rhs.data;
return res;
}
A operator - (const A& lhs,double rhs)
{
A res(0);
res.data = lhs.data - rhs;
return res;
}
A operator - (double lhs,const A& rhs)
{
A res(0);
res.data = lhs - rhs.data;
return res;
}
ostream& operator << (ostream& fout,A& a)
{
fout << a.data ;
return fout;
}
int main(int argc, char* argv[])
{
A a(2.3);
A b(1.2);
A d(3.4);
A c;
c = a + b + d;
c=a+b;
c=a+1.0;
c=a-b;
c=a-1.0;
c=a*b;
c=a*1.0;
cout << c << endl;
c=1.0+2.0*a*a-3.0*a*b;
cout << c << endl;
return 0;
}