运算符在c ++中重载+和+ =

Umu*_*mut 1 c++ operator-overloading

我对操作员操作概念非常陌生,之前提出的相关问题远远超过我,所以我需要提出一个基本问题.

这是.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
Run Code Online (Sandbox Code Playgroud)

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

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

如果你能纠正这个+=并给我写一个+重载实现,我真的很感激.我只需要将t,d,e值添加为Account对象.

Luc*_*ore 6

如果您想要operator+作为免费功能,您需要:

friend Account operator+ (const Account &acc, const Account &secondAcc);
Run Code Online (Sandbox Code Playgroud)

此外,它operator +是一个二元运算符,因此它不可能只接收一个参数.即使是成员函数,它只需要2个参数,只需要第一个参数,即可this在引擎盖下传递.

那么,你有两个选择:

1)会员运营商

class Account{
    Account operator+ (const Account &acc);
};
Run Code Online (Sandbox Code Playgroud)

2)自由运营商

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

Account operator+ (const Account &acc, const Account &secondAcc)
{
}
Run Code Online (Sandbox Code Playgroud)

非常重要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;

}
Run Code Online (Sandbox Code Playgroud)

这段代码会泄露.为什么不使用自动存储变量:

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

仍然不确定内部的逻辑,但至少它不泄漏内存.你现在的方式是修改参数,而不是你调用的对象+=.所以后,说,a+=b,a仍然是相同的,b将被修改.