分别用友元函数和成员函数实现运算符重载:
关键字
:friend、operator
注意:
比较分别用成员函数和用友元函数实现运算符重载的区别,特别是参数列表。
不同运算符重载的规则:
运算符 | 实现方法 |
---|---|
<< 和 >> | 必须用友元函数 |
‘=’ ‘( )’ ‘->’ ‘[]’ | 必须用成员函数 |
一元运算符和带‘=’的运算符 | 成员函数 |
二元运算符 | 友元函数 |
. 和 * 和 ? 和 :: 和 sizeof | 不能重载的运算符 |
'+'的运算符重载,用友元函数实现
#include <iostream>
using namespace std;
class Point4
{
private:
int x;
int y;
public:
Point4(); //默认的构造函数
void show_Point4();//打印对象的数据
Point4(int x, int y);//带参数的构造函数
friend Point4 operator +(const Point4 &a, const Point4 &b);//用友元函数来运算符重载
~Point4();
};
Point4 operator +(const Point4 &a, const Point4 &b);
//主函数
int main(){
Point4 p1(1, 2);
Point4 p2(2, 2);
(p1 + p2).show_Point4();
}
//函数定义
Point4::Point4(){ //默认的构造函数
cout << "Point4 constructor" << endl;
}
Point4::Point4(int x, int y) //带参数的构造函数
{
this->x = x;
this->y = y;
cout << "Point4 constructor with param" << endl;
}
void Point4::show_Point4(){
cout << "(" << this->x << "," << this->y << ")" << endl;
}
Point4 operator +(const Point4 &a, const Point4 &b){ //用友元函数去运算符重载
int nx = a.x + b.x;
int ny = a.y + b.y;
return Point4(nx, ny);
}
Point4::~Point4(){ //析构函数
cout << "Point4 destory" << endl;
}
'<<'运算符重载,必须用友元函数实现:
#include <iostream>
using namespace std;
class Point6
{
private:
int x, y;
public:
Point6();
Point6(int x, int y);
~Point6();
void show_Point6();
friend ostream& operator <<(ostream &cout, const Point6 &obj);//用友元函数实现'<<'运算符重载
};
ostream& operator <<(ostream &cout, const Point6 &obj);
int main(){
Point6 p5(3,4);
cout << p5;
return 0;
}
Point6::Point6()
{
cout << "Point6 constructor" << endl;
}
Point6::Point6(int x, int y){
this->x = x;
this->y = y;
cout << "Point6 constructor with param" << endl;
}
void Point6::show_Point6(){//打印出对象成员
cout << "(" << this->x << "," << this->y << ")" << endl;
}
ostream &operator <<(ostream &cout, const Point6 &obj){
cout << "(" << obj.x << "," << obj.y << ")" << endl;
return cout;
}
Point6::~Point6(){
cout << "Point6 destory" << endl;
}
用成员函数实现’-'运算符重载:
#include <iostream>
using namespace std;
class Point5
{
private:
int dx, dy;
public:
Point5();
void show_Point5();
Point5(int dx, int dy);
Point5 operator -(const Point5 &b);//运算符重载
~Point5();
};
int main(){
Point5 p3(1,2);
Point5 p4(2,4);
(p4 - p3).show_Point5();
}
void Point5::show_Point5(){
cout << "(" << this->dx << "," << this->dy << ")" << endl;
}
Point5::Point5(){ //默认的构造函数
cout << "Point5 constructor" << endl;
}
Point5 Point5::operator -(const Point5 &b){ //用友元函数去运算符重载
int nx = this->dx - b.dx;
int ny = this->dy - b.dy;
return Point5(nx, ny);
}
Point5::Point5(int dx, int dy) //带参数的构造函数
{
this->dx = dx;
this->dy = dy;
cout << "Point5 constructor with param" << endl;
}
Point5::~Point5(){//析构函数
cout << "Point5 destory" << endl;
}
用成员函数实现自增运算符“++重载”: