C++ 中的运算符重载 + 和 +=
operator overloading + and += in c++
我对运算符操作加载概念非常陌生,之前提出的相关问题远远领先于我,所以我需要问一个基本问题。
这是 .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
。
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用