我正在尝试完成一个程序,程序崩溃,我找不到逻辑错误

时间:2015-06-24 22:41:45

标签: c++ arrays templates

#include <iostream>
#include <stdexcept>

using namespace std;

//implement the functions directly in the class declaration below
template <typename T>
class Array
{
public:
    Array(int s)
    {
    this->size = s;
    elements = new T [size];

    cout << "Array was created " << *this << endl;
    }
    Array(const Array& right)
    {
    this->initElements(right);

    cout << "Array was copy constructed " << *this << endl;
    }
    Array& operator=(const Array& right)
    {
        if(this != &right)
    {
        this->freeArray();
        this->initElements(right);

        cout << "Array has new values = " << *this << endl;
    }
    return *this;
    }

    virtual ~Array()
    {
    this->freeArray();

    cout << "Array was destroyed" << endl;
    }

    T& operator[](int index)
    {
        if(index > -1 || index < size)
        {
            return this->elements[index];
        }
        else
                    throw out_of_range("Out of range");
    }

    T& operator[](int index) const
    {
        if(index > -1 || index < size)
        {
        return this->elements[index];
        }
        else
            {
                throw out_of_range("Out of range");
            }
    }

    T& getElements()
    {
        return this->elements;
    }

    int get_size() const
    {
        return this->size;
    }

    void sort_array()
    {
        for(int i = 0; i < this->size ; i++)
        {
            for(int j = i+1 ; j < this->size-1 ; j++)
            {
                if(elements[j]< elements[i])
                {
                    swap(elements[i],elements[j]);
                }
            }
        }
    }
private:
    T *elements;
    int size;
    void freeArray()
    {
        delete [] this->elements;
    }
    void initElements(const Array& other)
    {
    this->elements = new T [other.get_size()];
    for(int i = 0; i < other.get_size(); i++)
        this->elements[i] = other.elements[i];
    }
};

template <typename T>
ostream& operator<<(ostream& os, Array<T> arr)
{
    os << "Array::=(" ;
    for(int i = 0 ; i < arr.get_size() ; i ++)
    {
        os << arr[i] << ", ";
    }
    os << ")" << endl;
    return os;
}



int main()
{
    //do not change this
    Array<int> arr(5);
    arr[0] = 1;
    arr[1] = 2;

    cout << arr << endl;
    cout << "arr.size= " << arr.get_size() << endl;

    try
    {
        cout << arr[6] << endl;
    }
    catch (const out_of_range& e)
    {
        cout << "6 is out of range" << endl;
    }

    arr.sort_array();
    cout << arr << endl;

    return 0;
}

这是我在C ++上的程序,它是一个需要作为模板的数组,运行后我得到一个错误并且不知道为什么......我需要快速检查它,如果有人可以告诉我我的问题是什么,在哪里?

1 个答案:

答案 0 :(得分:0)

ostream& operator<<(ostream& os, Array<T> arr)获取arr的副本,触发复制构造函数。复制构造函数还尝试使用触发复制构造函数的<<运算符进行打印。在你崩溃之前不受控制的递归。

可能只是一个错字,但传递参考。 ostream& operator<<(ostream& os, Array<T> & arr)