C++中的运算符重载
关于C++的运算符有哪些大家可以参考以下文章
https://www.cnblogs.com/mengqingxiang/p/15117843.html
关于C++的的运算符重载,就是根据不同的场景为运算符增加一些新的功能,C++中的全局函数和成员函数都是支持运算符重载的,具体根据使用场景的不同决定使用哪种,通常需要对操作符2侧的输入都需要定制的,通常设置为全局函数(成员函数无法实现,例如重载<<运算符来打印到输出窗口),而对于那些和对象本身紧密相关的操作符通常设置为成员函数(例如==,>,<等)。
Example:
class Point {
friend ostream & operator<<(ostream &cout,const Point &);
private:
int m_x;
int m_y;
public:
Point(int x,int y):m_x(x),m_y(y){}
bool operator==(const Point &);
};
ostream & operator<<(ostream &cout,const Point &point){
cout << "(" << point.m_x << "," << point.m_y << ")";
return cout;
}
bool Point::operator==(const Point &point) {
return (m_x == point.m_x) && (m_y == point.m_y);
}
int main(){
Point p1(10,10);
Point p2(10,10);
cout << (p1==p2) << endl;
cout << p1 << endl;
return 0;
}
//输出:
1
(10,10)
如何调用父类的运算符重载函数
class ThreeDimensional:Point
{
private:
int m_z;
public:
ThreeDimensional(int x,int y,int z);
bool operator==(const ThreeDimensional &point);
};
ThreeDimensional::ThreeDimensional(int x,int y,int z):Point(x,y),m_z(z)
{
}
bool ThreeDimensional::operator==(const ThreeDimensional &point) {
return (Point::operator==(point)) && (m_z == point.m_z);
}
int main(){
ThreeDimensional p1(10,10,10);
ThreeDimensional p2(10,10,10);
ThreeDimensional p3(10,20,10);
cout << (p1==p2) << endl;
cout << (p1==p3) << endl;
return 0;
}
//打印
1
0
运算符重载的注意点
有些运算符无法重载
1.对象成员访问运算符:.
2.域运算符:::
3.三目运算符:?:
4.sizeof
只能重载为成员函数的如下:
1.赋值运算符:=
2.下标运算符:[]
3.函数运算符:()
4.指针访问成员:->
利用函数重载实现仿函数
把对象当做一个函数使用,实现关键是重载函数运算符(),作为对象可以保存状态,通常可以用于工厂类内部
class Obj
{
public:
Obj() {};
~Obj() {};
};
class Test{
public:
explicit Test(char type) : m_type(type){}
Obj* operator() (int a,int b){ //实现工厂模式中,利用不同的type返回不同的对象
Obj *obj = nullptr;
switch(m_type)
{
case 'i':
obj = new Obj();
break;
case 'o':
obj = new Obj();
break;
}
return obj;
}
private:
const char m_type;
};

浙公网安备 33010602011771号