这个一个简单的运算符重载,写在类里面,同样也可以写在类外面,不过不推荐
class Test
{
public:
friend Test& operator+(Test& a, Test &b);
Test(int a, int b)
{
this->a = a;
this->b = b;
}
//写在类里面
Test& operator-(Test& test)
{
a = a - test.a;
b = b - test.b;
return *this;
}
private:
int a;
int b;
};
//如果写在外面 需要在类里面定义友元函数
Test& operator+(Test& first, Test &second)
{
first.a = first.a + second.a;
first.b = first.b + second.a;
return first;
}
上面两种是简单的运算符重载,下面说一下特殊的运算符重载
前置++ 和后置 ++重载 , 后置++ 需要在参数里面加一个int的占位符,这是编写c++的大佬们为了区分前置后置,记着就行,
--同样如此
//前置++
Test& operator++()
{
a++;
b++;
return *this;
}
//后置++
Test& operator++(int)
{
a++;
b++;
return *this;
}
<< >>重载左移右移运算符,这个其实是重载iostream类的运算符,让cout<< cin<<的时候出现我们想要的结果,类似于c#的重写tostring方法
class Test
{
public:
//同样需要在类里面声明友元函数
friend istream & operator>>(istream &in, Test &obj);
friend ostream & operator<<(ostream &out, Test &obj);
重点提示!!!<< >>运算符重载不要写在类的内部,原因我也不清楚,会报很奇怪的bug,如果硬要写在类的内部,需要多些很多步骤,所以不建议写在类的内部,下面的函数实现,返回值是引用,以便可以cout << t1 << t2 的输出链
ostream & operator<<(ostream &out, Test &obj)
{
out << obj.a << " " << obj.b;
return out;
}
istream & operator>>(istream &in, Test &obj)
{
in >> obj.a >> obj.b;
return in;
}
Tips:
c++中不能用友元函数重载的运算符有 = () [] ->,一般我们只有左移右移运算符使用友元函数重载逻辑与 逻辑或 && || 系统自带的操作符会有短路规则 但是自己重载的操作符无法实现
重载等号操作符,一般用来做深拷贝 先把原来内存释放掉 ,再分配内存,具体可以看我
深浅拷贝的博客
只有函数的返回值是引用的时候才可以当左值,所以如果想要连续的 加减或者<< 返回值要写成引用