运算符重载未处理的异常

时间:2013-12-22 11:36:37

标签: c++ overloading

我在重载+运算符时遇到了一些麻烦。我收到运行时错误。未处理的异常后跟内存地址。

以下是我编码的内容:

#include <iostream>
#include <iomanip>
using namespace std;


class myVector{

    int vsize, maxsize;
    int* array;
    void alloc_new();

    friend ostream& operator<< (ostream &out, myVector&);
    friend istream& operator>> (istream &in, myVector&);


public:
     myVector();
     myVector(int);
    myVector(const myVector&);   //copy constructor
    ~myVector();
    void push_back(int);
    int size();
    int operator[](int);
    myVector operator+(myVector&);
    int at(int i);
};

 myVector::myVector()
{
    maxsize = 20;
    array = new int[maxsize];
    vsize = 0;

}

myVector::myVector(int i)
{

    maxsize = i;
    array = new int[maxsize];
    vsize = 0;

}

myVector::myVector(const myVector& v){}

myVector::~myVector()
{
    delete[] array;
}

void myVector::push_back(int i)
{

    if (vsize + 1 > maxsize)
        alloc_new();
    array[vsize] = i;
    vsize++;
}

int myVector::operator[](int i)
{
    return array[i];
}

int myVector::at(int i)
{
    if (i < vsize)
        return array[i];
        throw 10;
}

void myVector::alloc_new()
{
    maxsize = vsize * 2;
    int* tmp = new int[maxsize];
    for (int i = 0; i < vsize; i++)
        tmp[i] = array[i];
    delete[] array;
    array = tmp;
}

int myVector::size()
{
    return vsize;
}

myVector myVector::operator+(myVector& a)
{
    myVector result;
    for (int i = 0; i < a.size(); i++)
        result.array[i] = this->array[i] + a.array[i];
    return result;

}

ostream& operator<< (ostream &out, myVector& a)
{ 
    for (int i = 0; i < a.size(); i++)
        out << a[i] << " ";
    return out;
}

istream& operator>> (istream &in, myVector& a)
{
    int tmp, lol;
    cin >> tmp;

    for (int i = 0; i < tmp; i++)
    {
        cin >> lol;
        a.push_back(lol);
    }
    return in;
}



int main()
{

    myVector vec;
    myVector vec2;
    myVector c;
    int width = 15;

    cout << "Input vector a\n";
    cin >> vec;                                                 // In: 3 1 2 3

    cout << "Input vector b\n";
    cin >> vec2;                                                    // In: 3 4 5 6

    cout << setw(width) << "Vector a: " << vec << endl;
    cout << setw(width) << "Vector b: " << vec2 << endl;


    cout << setw(width) << "c = a + b: " << c << endl;
    c = vec + vec2;


    system("PAUSE");
    return 0;
}

我如何为动态数组编写复制构造函数?这就是我现在所拥有的:

    myVector::myVector(const myVector &initial)
{
    int* tmp = new int[3];
    for (int i = 0; i < 3; i++)
        tmp[i] = initial.array[i];
    delete[] array;
    array = tmp;

}

1 个答案:

答案 0 :(得分:2)

当您在运算符+中分配结果时,您没有在结果向量中保留空间。

(你应该在运行时检查(断言或类似)中对你的类进行理智检查 - 检查每个方法的所有输入。这将显示你的结果索引器传入了一个在向量中不存在的索引。)