0

Нужен шаблон класс 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)]’ Сборка завершилась с ошибкой.

1 ответ 1

1

Вариант 1.

template <class T>
class vector2x
{
public:
    vector2x() {}
   ~vector2x() {}
   // тут еще должны быть всякие полезные перегрузки.
private:
   std::vector <std::vector <T> > internal;
};

Вариант 2.

Обходим ошибку

2.cpp:22:52: ошибка: ‘const T& Array<T>::operator[](int, int) const’ должен иметь ровно один аргумент

struct Index
{
     int x;
     int y;
     Index(int ex, int why) : x(ex), y(why) {}
     bool operator == (const Index& i)
         { return x == i.x && y = i.y;}
}

class WorksFine
{
...
public:
     Foo& operator [] (Index i);
};

array[Index(10,10)].MemberOfFoo(); //работает
array[Index(4,2)] = foo; // не работает. Требует lvalue. Упс. Нужно дорабатывать.

Далее дорабатываем:

http://com-inform.narod.ru/ccc/86.htm

http://com-inform.narod.ru/ccc/87.htm

Все! Теперь у нас настоящий массив. По крайней мере нечто, что выглядит как настоящий массив :-)

8
  • Нельзя использовать встроенные шаблоны по заданию. Ни вектора, ни карты, ничего.
    – Tomagavk
    30 мая 2011 в 22:26
  • А Вы свой исходный Array подставьте вместо вектора :-o И счастье настанет
    – gecube
    30 мая 2011 в 22:29
  • Вау, мне чертовски нравится это решение!) Даже если не работает- подход весьма интересен! //побежал тестить
    – Tomagavk
    30 мая 2011 в 22:30
  • T& operator [] (Index i) { if (i.x>=0&&i.x<GetSizeL()) if (i.y>=0&&i.y<GetSizeW()) return pType[Index(i.x,i.y)]; throw xBoundary(); return pType[0,0]; } Ругается на return pType[Index(i.x,i.y)]; >>error: no match for ‘operator[]’ in ‘((Array<int>*)this)->Array<int>::pType[Index(i.Index::x, i.Index::y)]’
    – Tomagavk
    30 мая 2011 в 22:48
  • Ну, так правильно. Вы не там оператор [] перегружаете для двумерного индекса. Его нужно перегрузить для vector2x - отдельного класса для двумерных массивов. А базовый класс для одномерных массивов должен уметь operator[](int)<p> Ах да. Чтобы вставить символы \< и \> в комментарий пишите: \\\< и \\\> соответственно. С [ и ] аналогично.
    – gecube
    30 мая 2011 в 23:04

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.