奇怪的运行时错误

时间:2012-02-23 01:02:22

标签: c++

我在运行非常简单的c ++程序时遇到了麻烦。它是一个BigInt类,它接受一个字符串作为输入,并将每个单独的数字设置为动态数组。我到目前为止所做的就是输入BigInt然后输出它......非常简单。我的程序编译并运行得很好但是一旦我输入我的第一个输入它就给我这个奇怪的错误......“这个应用程序已经请求Runtime以一种不寻常的方式终止它。 请联系应用程序的支持团队获取更多信息。“

我不知道如何解决这个问题,因为我在代码中找不到任何瑕疵。

有人有什么想法吗?

继承我的代码:

HEADER FILE:

#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;
}

2 个答案:

答案 0 :(得分:3)

这一行错了:

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

在i等于零时,你要求从-1开始的子串。

答案 1 :(得分:0)

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

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

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

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