== , > , >= , < , <= , != , ++ , – , + , - , cout的<<和 >> =
重载运算符,本子上是一个函数。整个函数的名字:operator关键字+运算符,既然重载运算符本质上是一个函数,那么会有返回类型和参数列表。
#include <iostream>
using namespace std;
class A
{
public:
A(int a) :m_a(a){ }
void matest(int n);
A& operator =(const A&);
void macout()
{
cout << m_a << endl;
}
private:
int m_a;
};
A& A::operator=(const A& tmpobj)
{
cout << "赋值运算符重载" << endl;
return *this;//返回对象本身
}
void A::matest(int n)
{
this->m_a = n;
}
int main()
{
A a1(1);
A a2(2);
a1 = a2;//a1就是this对象,a2就是operator=里面的参数
a1.macout();
a2.macout();
return 0;
}
赋值运算符重载
1
2
以上结果可以看见,重载=运算符后该并没有进行赋值,因为重载函数里没有进行相应的操作,修改成如下代码则完成对象的赋值。
A& A::operator=(const A& tmpobj)
{
cout << "赋值运算符重载" << endl;
this->m_a = tmpobj.m_a;
return *this;//返回对象本身
}