我试图让这段代码在 GNU C++ 编译器 (g++) 中编译,但它似乎不起作用。我用过 Vis Studio 和 Code::Blocks,它工作得很好。我知道编译器在某些方面有所不同,并且想知道是否有人可以帮助我找到我的错误。
#include <iostream>
using namespace std;
template <class T>
class Array
{
private:
T *m_array;
int m_size;
public:
Array();
Array(Array& other);
Array(int size);
~Array();
void setValue(int index, T val);
T getValue(int index);
int getSize();
Array &operator=(Array &other);
Array &operator+(Array &other);
Array &operator+(T val);
inline friend ostream &operator<<(ostream &other, Array<T> arr)
{
for (int i = 0; i < arr.getSize(); i++)
{
other << arr.getValue(i) << " ";
}
}
};
template<class T>
Array<T>::Array()
{
m_array = NULL;
m_size = 0;
}
template<class T>
Array<T>::Array(int size)
{
m_size = size;
m_array = new T[size];
}
template<class T>
Array<T>::Array(Array& other)
{
*this = other;
}
template<class T>
Array<T>::~Array()
{
delete[] m_array;
}
template<class T>
void Array<T>::setValue( int index, T val )
{
m_array[index] = val;
}
template<class T>
T Array<T>::getValue( int index )
{
return m_array[index];
}
template<class T>
Array<T> &Array<T>::operator=( Array& other )
{
if (m_array != NULL)
delete[] m_array;
m_size = other.getSize();
m_array = new T[m_size];
for (int i = 0; i < other.getSize(); i++)
{
m_array[i] = other.getValue(i);
}
return *this;
}
template<class T>
Array<T> &Array<T>::operator+( Array &other )
{
for (int i = 0; i < m_size; i++)
{
m_array[i] += other.getValue(i);
}
return *this;
}
template<class T>
Array<T> &Array<T>::operator+( T val )
{
for (int i = 0; i < m_size; i++)
{
m_array[i] += val;
}
return *this;
}
template<class T>
int Array<T>::getSize()
{
return m_size;
}