在 class 中创建 operator+ 而无需声明那么多不必要的变量的最佳方法

best way to create an operator+ inside a class without declaring so many unnecessary variables

所以我们得到了一个问题,我们有一个 class 名为 Cocktail 的名称和音量属性。现在他们希望我们“写一个重载运算符加法来混合两种鸡尾酒,即将两种鸡尾酒加在一起给出: 鸡尾酒 1 的体积 + 鸡尾酒 2 的体积是结果的体积和鸡尾酒 1 的名称 + "mixed with " + 鸡尾酒 2 的名称作为结果名称。 他们说对 class Cocktail 进行所有必要的假设。(我假设有私有属性 name 和 volume。)但是 class Cocktail 中还没有任何其他重载函数。 这是否意味着我可以定义两个运算符? 因为我正在考虑创建一个内部运算符 +=,然后在我的外部运算符 + 中调用它,这在我看来是最合乎逻辑的解决方案:

//inside my class Cocktail, INTERNAL OPERATOR
Cocktail& operator+=(Cocktail const& c1){
    name = name + "mixed with" + c1.name; 
    volume = volume + c1.volume; 
    return *this; 
}

//external operator

const Cocktail operator+(Cocktail c1, Cocktail const& c2){
    c1+=c2; 
    return c1; 
}

但我不知道他们的指示是否允许我制作两个。所以我试着做一个内部运算符,我唯一能想到的就是必须在定义中声明一个新的鸡尾酒,然后按如下方式返回它的值:

//internal operator

Cocktail operator+(Cocktail const& other) const {
   Cocktail c; 
   c.name = name + "mixed with" + other.name; 
   c.volume = volume + other.volume; 
   return c; 
}

但我觉得这很奇怪,所以我想也许这样会更好,但我开始怀疑我的下一个选项是否会编译:

//internal operator
Cocktail& operator+(Cocktail const& c){
    name = name + "mixed with" + c.name; 
    volume = volume + c.volume; 
    return *this; 
}  

我有权这样做吗? 哪个是定义运算符的最佳方式? 有没有更好的办法? 谢谢

   Cocktail operator+(Cocktail const& other) const {
      Cocktail c; 
      c.name = name + "mixed with" + other.name; 
      c.volume = volume + other.volume; 
      return c; 
   }

这是实现二元+运算符的正确方法。想象一下:你用另外两种鸡尾酒调制了一种新鸡尾酒。

如果你想在另一种鸡尾酒中加入一种鸡尾酒,运算符 += 是正确的。

但根据你的任务,我想第一个会更好。

更喜欢这种方法。

const Cocktail operator+(Cocktail c1, Cocktail const& c2){
    return c1+=c2; 
}
  • 它不重复代码。
  • 它允许对 c1c2 进行相同的隐式转换。 (*this 不隐式转换)
  • 它允许 c1
  • 的移动语义或复制省略
  • 它允许更好的封装