重载的运算符是成员函数时

scorlw 发布于

重载的运算符是成员函数时

c++

当重载的运算符是成员函数时,this绑定到左侧运算符对象(例如重载+运算符,则默认+左侧的参数为this(或者this的成员))。成员运算符函数的参数数量比运算符对象的数量少一个;至少含有一个类类型的参数;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class CWeight
{
public:
CWeight(int iIn){m_iWeight = iIn;};
CWeight operator+(const CWeight& other);
CWeight& operator=(const CWeight& other);
public:
int m_iWeight;
};
CWeight CWeight::operator+(const CWeight& other)
{
return CWeight(this->m_iWeight + other.m_iWeight); // 注意这里, 调用了实际的加法,但是本实例的数据作为了左操作数, 我特意加了this->,其实是可以省略的.
}
CWeight& CWeight::operator=(const CWeight& other)
{
m_iWeight = other.m_iWeight;
return *this;
}

int main()
{
CWeight w1(10);
CWeight w2(20);
CWeight w3 = w1 + w2;
printf("w1 = %d, w2 = %d, w3 = %d\n", w1.m_iWeight, w2.m_iWeight, w3.m_iWeight);
system("pause");
return 0;
}

输出:

1
w1 = 10, w2 = 20, w3 = 30