加号运算符重载
成员函数实现
#include <iostream>
using namespace std;
class Person {
public :
int a;
int b;
Person ( ) { }
Person ( int a, int b)
{
this - > a = a;
this - > b = b;
}
Person operator + ( const Person& p)
{
Person temp;
temp. a = this - > a + p. a;
temp. b = this - > b + p. b;
return temp;
}
Person operator + ( int val)
{
Person temp;
temp. a = this - > a + val;
temp. b = this - > b + val;
return temp;
}
} ;
int main ( )
{
Person p1 ( 10 , 10 ) ;
Person p2 ( 10 , 10 ) ;
Person p3 = p1 + p2 + 20 ;
cout << "p3.a=" << p3. a << " p3.b=" << p3. b<< endl;
}
全局函数实现
#include <iostream>
using namespace std;
class Person {
public :
int a;
int b;
Person ( ) { }
Person ( int a, int b)
{
this - > a = a;
this - > b = b;
}
} ;
Person operator + ( const Person& p1, const Person& p2)
{
Person temp;
temp. a = p1. a + p2. a;
temp. b = p1. b + p2. b;
return temp;
}
Person operator + ( const Person& p1, int val)
{
Person temp;
temp. a = p1. a + val;
temp. b = p1. b + val;
return temp;
}
int main ( )
{
Person p1 ( 10 , 10 ) ;
Person p2 ( 10 , 10 ) ;
Person p3 = p1 + p2 + 20 ;
cout << "p3.a=" << p3. a << " p3.b=" << p3. b<< endl;
}
左移运算符重载
成员函数无法实现
class Person {
public :
int a;
int b;
Person ( int a, int b)
{
this - > a = a;
this - > b = b;
}
ostream& operator << ( Person& p)
{
cout << "p.a=" << p. a << " p.b=" << p. b << endl;
return cout;
}
} ;
全局函数实现
#include <iostream>
using namespace std;
class Person {
public :
int a;
int b;
Person ( int a, int b)
{
this - > a = a;
this - > b = b;
}
} ;
ostream& operator << ( ostream& out, Person& p)
{
out << "p.a=" << p. a<< " p.b=" << p. b<< endl;
return out;
}
int main ( )
{
Person p ( 10 , 20 ) ;
cout << p<< "hello world!" ;
}