【发布时间】:2015-06-10 11:57:50
【问题描述】:
我正在创建一个 HugeInt 类。我的主要:
#include <iostream>
#include <string>
int main(int argc, char* argv[])
{
HugeInt hi1("123");
HugeInt hi2("456");
std::cout << hi1 + hi2 << std::endl;
return 0;
}
还有我的 HugeInt 类:
#include <iostream>
#include <string>
#define SIZE 32
class HugeInt
{
friend std::ostream & operator<<(std::ostream &, const HugeInt &);
public:
HugeInt();
HugeInt(const char *);
~HugeInt();
HugeInt operator+(const HugeInt &) const;
private:
int * buffer;
int size;
};
和他的方法:
HugeInt::HugeInt()
{
size = SIZE;
buffer = new int[size];
for (int i = 0; i < size; i++) {
buffer[i] = 0;
}
}
HugeInt::HugeInt(const char * hugeNumber)
{
size = strlen(hugeNumber);
buffer = new int[size];
for (int i = size - 1; i >= 0; i--) {
buffer[i] = hugeNumber[i] - '0';
}
}
HugeInt::~HugeInt()
{
delete[] buffer;
}
HugeInt HugeInt::operator+(const HugeInt & operand) const
{
HugeInt temp;
int carry = 0;
if (size >= operand.size)
temp.size = size;
else
temp.size = operand.size;
for (int i = 0; i < temp.size; i++) {
temp.buffer[i] = buffer[i] + operand.buffer[i] + carry;
if (temp.buffer[i] > 9) {
temp.buffer[i] %= 10;
carry = 1;
}
else {
carry = 0;
}
}
return temp;
}
std::ostream & operator<<(std::ostream & output, const HugeInt & complex)
{
for (int i = 0; i < complex.size; i++)
output << complex.buffer[i];
return output;
};
一切都编译得很好。但控制台显示“-17891602-17891602-17891602”,然后出现错误“调试断言失败!....表达式:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)”。
当我们重新定义 operator+() 时,问题出在“return temp”。它有什么问题?
【问题讨论】:
标签: c++