在 C++ 中重载运算符

overloading an operator in C++

我正在阅读有关 C++ 中的运算符重载的信息,我已经阅读了很多教程文档和问答,但我找不到答案。 在下面的代码中:

class Box
{
   public:
      // Overload + operator to add two Box objects.
      Box operator+(const Box& b)
      {
         Box box;
         box.length = this->length + b.length;
         box.breadth = this->breadth + b.breadth;
         box.height = this->height + b.height;
         return box;
      }
};

int main( )
{
   Box Box1;
   Box Box2;
   Box Box3;

   // Add two object as follows:
   Box3 = Box1 + Box2;

   return 0;
}

如您所见,我们为 BOX class.When 覆盖了 + 运算符,我们在主函数中调用了覆盖运算符,class 实例之一用作 参数(Box1 或 Box2?)& this 访问哪个?实际上哪个叫覆盖运算符?为什么我们在参数中使用 & 关键字? WBR.

左边的操作数是 this 参数。为了避免这种晦涩难懂和一些更实际的重要问题,只需将此运算符定义为 class 之外的普通(运算符)函数。但是,修改的运算符,例如 +=,IMO 最好将其定义为 class 成员。


class 之外的定义:

class Box
{
private:
    // Data members, unspecified in the question.

public:
    // Public interface.
};

// Overload + operator to add two Box objects.
auto operator+( Box const& a, Box const& b)
    -> Box
{
    Box result;
    result.length  = a.length + b.length;
    result.breadth = a.breadth + b.breadth;
    result.height  = a.height + b.height;
    return result;
}

如果你的数据成员不是public(你没有指定任何相关内容),那么对于上面的class方法你需要添加一个friend 运算符函数的声明,在 class 中。例如

friend auto operator+( Box const& a, Box const& b) -> Box;

与class定义之外的效果几乎相同的替代方法是将运算符定义为class中的friend函数,如下所示:

class Box
{
private:
    // Data members, unspecified in the question.

public:
    // Public interface.

    friend
    auto operator+( Box const& a, Box const& b)
        -> Box
    {
        Box result;
        result.length  = a.length + b.length;
        result.breadth = a.breadth + b.breadth;
        result.height  = a.height + b.height;
        return result;
    }
};

在这里您不需要单独的 friend 声明。

另一个区别是这个在-class-定义的friend函数只能通过参数相关查找(ADL)找到,这意味着它并不容易,例如取它的地址。我不知道如何做到这一点。但至少 了解 这种方法对于理解某些习语是必要的,例如 Barton Nackman 基于 CRTP 的技巧,用于赋予 class 关系运算符。


回复

why we use & keyword in argument?

…这只是约定俗成,总的来说是一种优化,避免了一些不必要的数据拷贝。对于小型,在现代机器上,它可能会产生相反的效果。

Box operator+(const Box& b)

此处,加法运算符用于将两个 Box 对象和 return 最终 Box 对象相加。为此,一个对象作为参数传递,其属性将使用另一个对象访问。可以使用 this 运算符访问将调用此运算符 (+) 的对象 (Box1),而传递的参数是 Box2.