重载运算符 +在 C++
好的,我正在读一本书并尝试学习 C++ 运算符重载。我创建了一个 BigInt 类,它的构造函数采用单个 int (最初设置为 0)。我重载了 += 方法,它在以下代码中工作得很好:
BigInt x = BigInt(2);
x += x;
x.print( cout );
代码将输出 4。因此,然后我正在使用以下代码重载全局运算符 +:
BigInt operator+(const BigInt lhs, const BigInt rhs)
{
BigInt returnValue(lhs);
returnValue += rhs;
return returnValue;
}
这也适用于以下代码:
BigInt x = BigInt(1);
BigInt y = BigInt(5);
BigInt z = x + y;
z.print();
这会打印out 6. 但是,当我尝试执行以下代码时,它不起作用。这本书没有很好地解释,并且暗示它应该可以简单地工作。
BigInt x = BigInt(1);
BigInt z = x + 5;
z.print();
这打印出 1。我不知道为什么 z 是 1,而它应该是 6。我在网上和 stackoverflow 上搜索,但我找不到其他人遇到完全相同的问题。有些很接近,但答案就是不合适。非常感谢任何帮助!
Ok, I am working through a book and trying to learn C++ operator overloading. I created a BigInt class that takes a single int (initially set to 0) for the constructor. I overloaded the += method and it works just fine in the following code:
BigInt x = BigInt(2);
x += x;
x.print( cout );
The code will output 4. So, then I was working on overloading the global operator + using the following code:
BigInt operator+(const BigInt lhs, const BigInt rhs)
{
BigInt returnValue(lhs);
returnValue += rhs;
return returnValue;
}
This also works fine for the following code:
BigInt x = BigInt(1);
BigInt y = BigInt(5);
BigInt z = x + y;
z.print();
This prints out 6. However, when I try to execute the following code, it just doesn't work. The book doesn't explain very well and implies that it should simply work.
BigInt x = BigInt(1);
BigInt z = x + 5;
z.print();
This prints out 1. I'm not sure why z is 1 when it should be 6. I googled online and on stackoverflow but I couldn't find anyone else that was having a problem exactly like this. some were close, but the answers just didn't fit. Any help is much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最有可能的问题是在
+=
运算符中。发布它的代码。most likely problem is in
+=
operator. Post code for it.您需要一个重载来将 int 添加到 BigInt;您的示例中的常量 5 是 int 类型,而不是 BigInt 类型。像这样的东西应该可以工作:
您可能也需要一个operator+(const int lhs, const BigInt rhs) 。
You need an overload for adding an int to BigInt; the constant 5 in your example is of type int, not BigInt. Something like this should work:
You might want one for
operator+(const int lhs, const BigInt rhs)
too.以下超级简化的代码(我可以添加的最少代码,以包含您的所有代码并将其变成有效的独立可执行程序):
如可预测地发出:
请对此工作代码进行尽可能少的更改以重现您遇到的错误观察——这当然会显示你的错误到底在哪里。
The following super-simplified code (the minimum I can add to include all your code and make it into a valid stand-alone executable program):
emits, as predictable:
Please make the minimum possible alterations to this working code to reproduce the bug you observe -- that will of course show where your bug exactly lies.
您发布的代码看起来不错并且应该可以工作。您看到的问题几乎肯定是由于 BigInt 类的复制构造函数或赋值运算符造成的。
The code you've posted looks fine and should work. Problems you're seeing are almost certainly due to the copy constructor or assignment operator of your BigInt class.