gpt4 book ai didi

c++ - 运算符返回值问题

转载 作者:行者123 更新时间:2023-11-28 05:37:01 26 4
gpt4 key购买 nike

我在使用 += 运算符返回值时遇到问题。

下面是相关的具体代码。如果需要显示更多代码,我会提供:

    double operator+=(double b, const Account& c)
{
return b += c.getBalance();
}

主要实现的地方:

    for(int i = 0; i < NUMBER_OF_ACCOUNTS; i++)
{
std::cout << i+1 << "- " << (balance += *AC[i]) << std::endl;
}
std::cout << "Total Balance: " << balance << std::endl;

我收到的输出:

1- 10302.98
2- 10302.98
3- 201.00
Total Balance: 0.00

我想要得到的输出:

1- 10302.98
2- 20605.96
3- 20806.96
Total Balance: 20806.96

最佳答案

需要通过引用传入b:

double operator+=(double &b, const Account& c)
{
return b += c.getBalance();
}

代替

double operator+=(double b, const Account& c)
{
return b += c.getBalance();
}

否则,想想会发生什么,balance(0) 的值在每次调用时都会被复制进来,而不是您实际求和到别名为 balance 的内存位置.

关于c++ - 运算符返回值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38042839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com