简体   繁体   English

为什么我在这个 C++ 类中的重载 operator+ 不需要实现为 operator-?

[英]Why my overload operator+ in this c++ class doesn't need to be implemented as operator-?

friend complex operator +(complex &t1, complex &t2);

complex operator-(complex &t){
    complex tmp(this->a - t.a, this->b - t.b);
    return tmp;
}

I'm learning c++.我正在学习 C++。 I don't understand why operator+ don't need to be written as operator-?我不明白为什么 operator+ 不需要写成 operator-?

Both achieve the same goal.两者都实现了相同的目标。 In the first case, the global operator+ function is made friend of this class so it can access private members.在第一种情况下,全局operator+函数成为此类的friend ,因此它可以访问私有成员。 The second overloaded operator- is automatically called when '-' is used between two complex objects.当在两个complex对象之间使用“-”时,会自动调用第二个重载operator- -。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM