C++ 中的运算符重载 + 和 +=

operator overloading + and += in c++

本文关键字:重载 运算符 C++      更新时间:2023-10-16

我对运算符操作加载概念非常陌生,之前提出的相关问题远远领先于我,所以我需要问一个基本问题。

这是 .h 文件:

#define ACCOUNT_H
using namespace std;
class Account{
  friend Account &operator+ (Account &acc);
  friend ostream &operator<< (ostream &, Account &);
  public:
    Account(double=100.0,double=0.0,double=0.0);
    Account &returnSum(Account &otherAccount) const;
    Account& operator+=(Account &Acc1);
    void setT(double);
    void setD(double);
    void setE(double);
    double getT(void);
    double getD(void);
    double getE(void);
    void printAccount();
  private:
    double t;
    double d;
    double e;
};
#endif

我需要将+重载为"带有单个参数"的全局函数(这对我来说是具有挑战性的部分)并+=为成员函数(这里我假设我不能接受右侧操作数,因为它是一个成员函数,所以这是有问题的部分)。这是我对+=的实现:

Account &Account ::operator+=(Account &Acc1){
   Account *result = new Account(Acc1.getT()+t,Acc1.getD()+d,Acc1.getE()+e);
   Acc1 = *result;
   return *this;
}

如果您能纠正此+=并为我编写一个用于+重载的实现,我将不胜感激。我只需要将 t,d,e 值添加为帐户对象。

如果你想operator+作为一个自由函数,你需要:

friend Account operator+ (const Account &acc, const Account &secondAcc);

此外,operator +是一个二元运算符,因此它不可能只接收一个参数。即使当成员函数时,它也需要 2 个参数,只是第一个参数 this 在后台传递。

因此,您的两个选择:

1) 会员运营商

class Account{
    Account operator+ (const Account &acc);
};

2) 自由操作员

class Account{
    friend Account operator+ (const Account &acc, const Account &secondAcc);
};
Account operator+ (const Account &acc, const Account &secondAcc)
{
}

非常重要 1

请注意,我按值返回,而不是像您那样引用。这是为了防止 UB,因为您可能会返回一个局部变量,通过引用返回该变量是非法的。

非常重要的2

Account &Account ::operator+=(Account &Acc1){
   Account *result = new Account(Acc1.getT()+t,Acc1.getD()+d,Acc1.getE()+e);
   Acc1 = *result;
   return *this;
}

此代码将泄漏。为什么不使用自动存储变量:

Account &Account ::operator+=(Account &Acc1){
   Account result(Acc1.getT()+t,Acc1.getD()+d,Acc1.getE()+e);
   Acc1 = result;
   return *this;
}

仍然不确定里面的逻辑,但至少它不会泄漏内存。你现在拥有它的方式是,你正在修改参数,而不是你调用+=的对象。所以在a+=b之后,a仍然是一样的,b会被修改。

Account &Account ::operator+=(Account &Acc1){
   Account *result = new Account(Acc1.getT()+t,Acc1.getD()+d,Acc1.getE()+e);
   Acc1 = *result;
   return *this;
}

这里有两个大问题。一个是Luchian Grigore提到的泄漏。另一个是它的行为方式不符合 operator+= 应该表现的方式。问题是您正在修改Acc1.您应该修改this .以下代码在重载时的行为将非常奇怪:

Account total;
Account joes_account;
...
total += joes_account;

使用您的代码,joes_account更新的是总和而不是变量total