Нужен шаблон класс Array, являющийся аналогом двумерных массивов. Делать решил на основе одномерных. Убил полдня, но так и не смог. Основная проблема с перегрузкой оператора индексирования. Пробовал с помощью одномерных Array<array<int>>, тоже не удалось. Возможно я тупой. Подскажите пожалуйста, что изменить в имеющемся коде, либо свою идею (фрагмент кода, если не затруднит).
template < class T >
class Array
{
public:
//конструкторы
Array(int sizeL,int sizeW);
Array(const Array& rhs);
~Array() {delete [] pType;}
//операторы
Array& operator = (const Array&);
T& operator [] (int offsetL,int offsetW)
{
if (offsetL>=0&&offsetL<GetSizeL())
if (offsetW>=0&&offsetW<GetSizeW())
return pType[offsetL,offsetW];
throw xBoundary();
return pType[0,0];
}
const T& operator [] (int offsetL,int offsetW) const
{
if (offsetL>=0&&offsetL<GetSizeL())
if (offsetW>=0&&offsetW<GetSizeW())
return pType[offsetL,offsetW];
throw xBoundary();
return pType[0,0];
}
//дружественная функция для переопределения оператора вывода
template < class X > friend ostream& operator<< (ostream&, Array<X>&);
//методы доступа
int GetSizeL() const {return itsSizeL;}
int GetSizeW() const {return itsSizeW;}
//определение класса исключений с множественным наследованием
class xBoundary {}; //обращение к элементу вне массива
class xSize //ошибки связанные с заданием размера
{
public:
virtual void PrintError() {cout<<"Size error!\n";}
};
class xBig :public xSize
{
public:
virtual void PrintError() {cout<<"Entered size is big!\n";}
};
class xSmall :public xSize
{
public:
virtual void PrintError() {cout<<"Entered size is small!\n";}
};
class xZero :public xSmall
{
public:
virtual void PrintError() {cout<<"Can not be zero!\n";}
};
class xNegative :public xSize
{
public:
virtual void PrintError() {cout<<"Can not be negative!\n";}
};
private:
T *pType;
int itsSizeW;
int itsSizeL;
};
//определение конструкторов иметодов шаблона-класса Массив
template < class T >
ostream& operator << (ostream& output, Array<T>& theArray)
{
for (int i=0;i<theArray.GetSizeW();i++)
{
for (int j=0;j<theArray.GetSizeL();j++)
output<<theArray[i,j]<<endl;
output<<endl;
}
return output;
}
template < class T >
Array<T>::Array(int sizeL,int sizeW):
itsSizeL(sizeL),itsSizeW(sizeW)
{
//проверка на ошибки размера массива
if (sizeL==0||sizeW==0) throw xZero();
if (sizeL>100||sizeW>100) throw xBig();
if (sizeL<1||sizeW<1) throw xNegative();
if (sizeL<2||sizeW<2) throw xSmall();
pType=new T[sizeL][sizeW];
for (int i=0;i<itsSizeW;i++)
for (int j=0;j<itsSizeL;j++)
pType[i,j]=0;
}
template < class T >
Array<T>::Array(const Array& rhs)
{
itsSizeL=rhs.GetSizeL();
itsSizeW=rhs.GetSizeW();
pType=new T[itsSizeL,itsSizeW];
for (int i=0;i<itsSizeW;i++)
for (int j=0;j<itsSizeL;j++)
pType[i,j]=rhs[i,j];
}
template < class T >
Array<T>& Array<T>::operator = (const Array& rhs)
{
if (this==&rhs) return *this;
delete [] pType;
itsSizeL=rhs.GetSizeL();
itsSizeW=rhs.GetSizeW();
pType=new T[itsSizeL,itsSizeW];
for (int i=0;i<itsSizeW;i++)
for (int j=0;j<itsSizeL;j++)
pType[i,j]=rhs[i,j];
return *this;
}
//********************Главная функция***********************************
int main()
{
try //обработчик ошибок
{
Array<int> workArray(8,2);
for (int i=0;i<workArray.GetSizeW();i++)
for(int j=0;j<workArray.GetSizeL();j++)
cin>>workArray[i];
cout<<workArray<<endl;
}
catch (Array<int>::xBoundary) {cout<<"Boundary error!\n";}
catch (Array<int>::xSize& theException) {theException.PrintError();}
return 0;
}
Ошибки при компиляции:
g++ -Wall -c "sem2_lab4.cpp" (в каталоге: /host/labs/sem2_lab4)
sem2_lab4.cpp:17:44: error: ‘T& Array<t>::operator’ must take exactly one argument
sem2_lab4.cpp:25:52: error: ‘const T& Array<t>::operator const’ must take exactly one argument
sem2_lab4.cpp: In constructor ‘Array<t>::Array(int, int)’:
sem2_lab4.cpp:98:22: error: ‘sizeW’ cannot appear in a constant-expression sem2_lab4.cpp: In function ‘int main()’: sem2_lab4.cpp:137:27: error: no match for ‘operator[]’ in ‘workArray[i]’ sem2_lab4.cpp: In constructor ‘Array<t>::Array(int, int) [with T = int]’:
sem2_lab4.cpp:134:31: instantiated from here sem2_lab4.cpp:72:9: warning: ‘Array<int>::itsSizeL’ will be initialized after
sem2_lab4.cpp:71:9: warning: ‘int Array<int>::itsSizeW’
sem2_lab4.cpp:89:1: warning: when initialized here
sem2_lab4.cpp:134:31: instantiated from here sem2_lab4.cpp:101:7: warning: left-hand operand of comma has no effect sem2_lab4.cpp: In function ‘std::ostream& operator<<(std::ostream&, Array<t>&) [with T = int, std::ostream = std::basic_ostream<char>]’:
sem2_lab4.cpp:138:13: instantiated from here sem2_lab4.cpp:82:9: warning: left-hand operand of comma has no effect sem2_lab4.cpp:82:9: error: no match for ‘operator[]’ in ‘theArray[(0, j)]’ Сборка завершилась с ошибкой.