奇怪的运行时错误

Weird runtime error

本文关键字:运行时错误      更新时间:2023-10-16

我在运行我的纯c++程序时遇到问题。它是一个BigInt类,它接受一个字符串作为输入,并将每个单独的数字设置为一个动态数组。到目前为止,我所要做的就是输入一个BigInt,然后输出它……非常简单。我的程序编译和运行都很好,但一旦我输入第一个输入,就会出现这个奇怪的错误。。。"此应用程序已请求运行时以异常方式终止它。有关详细信息,请联系应用程序的支持团队。"

我不知道该怎么处理这个问题,因为我在代码中找不到任何缺陷。

有人有什么想法吗?

这是我的代码:

头文件:

#ifndef BIGINT_H
#define BIGINT_H
#include <iostream>
namespace JHall{
class BigInt {
public:
    BigInt(std::string s = "");
    BigInt(const BigInt& b);
    ~BigInt();
    void operator =(const BigInt& b);
    friend std::istream& operator >>(std::istream& in, BigInt& b);
    friend std::ostream& operator <<(std::ostream& out, const BigInt& b);
private:
    short* num;
    int cap;
    int size;
};
}
#endif  /* BIGINT_H */

实现文件:

#include "BigInt.h"
#include <cstdlib>
namespace JHall{
BigInt::BigInt(std::string s) 
{
    size = s.length();
    cap = 100;
    num = new short[cap];
    int place = 0;
    for(int i = size-1; i >= 0; i--)
        num[place++] = strtol(s.substr(i-1,1).c_str(), NULL, 10);
}
BigInt::BigInt(const BigInt& b) 
{
    size = b.size;
    cap = b.cap;
    for(int i = 0; i < size; i++)
        num[i] = b.num[i];
}
BigInt::~BigInt() 
{
    delete [] num;
}
void BigInt::operator =(const BigInt& b)
{
    if(cap != b.cap)
    {
        short* temp = new short[b.cap];
        for(int i = 0; i < b.cap; i++)
            temp[i] = b.num[i];
        delete [] num;
        num = temp;
    }
    for(int i = 0; i < cap; i++)
        num[i] = b.num[i];
    size = b.size;
    cap = b.cap;
}
std::istream& operator>>(std::istream& in, BigInt& b)
{
    std::string s;
    in>>s;
    b.size = s.length();
    int count = 0;
    for(int i = b.size-1; i >= 0; i--)
        b.num[count++] = strtol(s.substr(i-1,1).c_str(),NULL,10);
    return in;
}
std::ostream& operator<<(std::ostream& out, const BigInt& b)
{
    for(int i = b.size-1; i >= 0; i--)
        out<<b.num[i];
    return out;
}
}

主文件:

#include <cstdlib>
#include "BigInt.h"
using namespace std;
using namespace JHall;
/*
 * 
 */
int main(int argc, char** argv) 
{
    BigInt b1, b2;
    cout<<"Enter a large integer"<<endl;
    cin>>b1;
    cout<<"Enter another large integer"<<endl;
    cin>>b2;
    cout<<b1;
    cout<<b2;

    return 0;
}

此行错误:

for(int i = b.size-1; i >= 0; i--)
    b.num[count++] = strtol(s.substr(i-1,1).c_str(),NULL,10);

当i等于0时,您要求从-1开始的子字符串。

一个明显的错误是,您没有在复制构造函数中分配内存:如果每次都使用它,您很可能会崩溃。另一个相对明显的错误是,你假设最多有100个数字,这似乎是一个不必要的限制。赋值运算符似乎做了不必要的工作,通常会复制两次值。此外,使用子串和strtol()将单个数字从char转换为short似乎有点过头了。正确的方法是使用

int value = s[i] - '0';

此外,您应该考虑在构造函数中使用成员初始值设定项列表。当然,如果你有一个工作副本构造函数,你可能还想实现一个swap()方法,然后在你的赋值操作符中使用它:

BigInt& BigInt::operetor= (BigInt const& other) {
    BigInt(other).swap(*this);
    return *this;
}