Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.89/9: Рейтинг темы: голосов - 9, средняя оценка - 4.89
29 / 24 / 5
Регистрация: 15.10.2019
Сообщений: 268

Шаблонный класс динамического массива. Тип элементов char*

08.11.2022, 21:34. Показов 2291. Ответов 28
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Я тут в ступоре...
Вот мое полное задание:

В данной лабораторной работе необходимо разработать шаблонный класс в соответствии с
вариантом задания. Любой класс должен иметь конструктор копии и перегруженный оператор =.
Также класс должен содержать перегрузку оператора << для класса iostream, чтобы его можно было
выводить в консоль через стандартный поток вывода cout с указанием количества элементов и их
значений. В главной функции main обеспечить консольный интерфейс для тестирование всех
функций шаблонного класса с типами int, float, char*, struct Vec2 {float x; float y;} (аналогично лаб 1)
Non-type параметр при тестировании класса можно задавать через константу.

Динамический массив, использующий избыточное резервирование памяти под элементы.
Увеличивает ёмкость на количество элементов, заданных в non-type параметре.
Необходимые методы:
reserve(n) – зарезервировать ещё n элементов
getCapacity() – получить текущую ёмкость
getLength() – получить текущую длину
insert(elem,n) – добавить элемент на позицию n
remove(elem,n) – удалить элемент на позиции n
Перегрузить следующие операции:
+ – добавить элемент в конец массива
- – удалить первое вхождение элемента в массиве (для типа char* должна быть своя специализация шаблона)
[] – доступ к элементу по индексу
== и != – проверка на идентичность и не идентичность массивов (для типа char* должна быть
своя специализация шаблона)

Местами есть приписка, что нужна обязательна специализация шаблона для char*, но у меня без этого все работает. Поэтому вопрос, специализация действительно нужна? Или это могли дать так, чисто ради задания?

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#include <iostream>
#include <cstring>
 
using namespace std;
 
struct Vec2;
 
 
template <typename T, int Nup>
class DynArray
{
  T* array;
  int Capacity;
  int length = 0;
 
  void alloc(int newCapacity)
  {
    if (newCapacity <= Capacity) return;
    T* newArray = new T[newCapacity];
    for(int i = 0; i < newCapacity; ++i)
    {
      if (i < Capacity)
      {
        newArray[i] = array[i];
      }
      else
      {
        newArray[i] = 0;
      }
    }
    delete[] array;
    array = newArray;
    Capacity = newCapacity;
  }
 
  void malloc()
  {
    array = new T[Capacity];
    for(int i = 0; i < Capacity; ++i)
      array[i] = 0;
  }
 
public:
 
  DynArray(int Capacity=0) : Capacity(Capacity)
  {
    malloc();
  }
 
  DynArray(DynArray& otherObj)
  {
          cout<<endl<<"copy ctor!"<<endl;
          Capacity = otherObj.getCapacity();
          malloc();
          length = otherObj.getLength();
          for (int i = 0; i < length; ++i)
          {
            array[i] = otherObj[i];
          }
  }
  
    DynArray& operator= (DynArray& otherObj)
    {
        if ( &otherObj != this)
        {
            cout<<endl<<"oper prisvo!"<<endl;
            delete[] array;
            Capacity = otherObj.getCapacity();
              malloc();
              length = otherObj.getLength();
              for (int i = 0; i < length; ++i)
              {
                array[i] = otherObj[i];
              }
        }
        else
        {
            cout << "Была остановленна попытка самоприсваиванья. " << endl;
        }
        
        return *this;
    }
 
  ~DynArray() { delete[] array; }
 
  T& operator[](int index) const
  {
    return array[index];
  }
 
  void reserve(int n) { alloc(Capacity + Nup); }
 
  DynArray& insert(T elem, int pos = -1)
  {
    pos = pos < 0 ? length : pos;
    //alloc(length + 1);
    if (Capacity < length + 1) { alloc(length + Nup); }
    for(int i = length - 2; i >= pos; ++i)
      array[i+1] = array[i];
    array[pos] = elem;
    length += 1;
    return *this; 
  }
  
  DynArray& operator+ (T elem)
  {
    insert(elem);
    return *this;
  }
  
  DynArray& remove(const T& elem, int pos = -1)
  {
    if(pos == -1)
    {
        for(int i = 0; i < length; ++i)
        {
            if(elem == array[i])
            {
                pos = i;
                break;
            }
        }
    }
    if(pos != -1 && pos < length)
    {
        for(int i = pos + 1; i < length; ++i)
        {
            array[i - 1] = array[i];
        }
        length -= 1;
    }
    return *this;
  }
    
  DynArray& operator- (T elem)
  {
    remove(elem);
    return *this;
  } 
  
 
  void print();
  int getLength() const { return length; }
  int getCapacity() const { return Capacity; }
  bool isEmpty() const { return length == 0; }  
  
  bool operator== (DynArray<T, Nup>& b)
    {
        if (this->getLength() == b.getLength())
        {
            for(int i=0; i < b.getLength(); ++i)
            {
                if (array[i] != b[i])
                {
                    return false; break;
                }
            }
            return true;
        }
        else
        {
            return false;
        }
    }
    
    bool operator!= (DynArray<T, Nup>& b)
    {
        if (this->getLength() == b.getLength())
        {
            for(int i=0; i < b.getLength(); ++i)
            {
                if (array[i] != b[i])
                {
                    return true; break;
                }
            }
            return false;
        }
        else
        {
            return true;
        }
    }   
 
  
  
};
 
 
 
 
template <typename T, int Nup>
void DynArray<T, Nup>::print()
{
  for(int i = 0; i < length; ++i)
    cout << array[i] << " ";
  cout << endl;
}
 
template <typename T, int Nup>
ostream& operator<<(ostream & os, const DynArray<T, Nup> & arr)
{
  for(int i = 0; i < arr.getLength(); ++i)
    cout << arr[i] << " ";
  cout << endl;
}
 
 
/*template <int Nup>
void DynArray<char*, Nup>::print()
{
  for(int i = 0; i < length; ++i)
    cout << array[i] << " ";
  cout << endl;
}*/
 
struct Vec2
{
  float x = 0, y = 0;
  
  Vec2(float a = 0) : x(a), y(a) {} 
  
  Vec2& operator=(float value)
  {
    x = y = value;
    return *this;
  }
  
  bool operator== (Vec2& b) const
    {
        if (x == b.x) {return true; }
        else { return false; }
    }
};
 
 
ostream& operator<<(ostream& os, const Vec2& vec)
{
  return os << " vec: " << vec.x << " " << vec.y;
}
 
int main(int argc, char** argv)
{
  system("chcp 1251");
    const int M = 3;
  cout << "Шаблон DynArray<int>:" << endl;
  DynArray<int, M> intArray(10);
  intArray+1+2+3;
  intArray.print();
  DynArray<int, M> iAr2(10);
  iAr2+2+3+4+1;
  cout << iAr2;
  intArray = iAr2;
  cout << intArray;
 
 
  
  cout << "check char*" << endl;
  DynArray<char*, M> ca(1);
  ca+"hi";
  ca+"world!";  
  cout << ca;
  ca-"world!";
  cout << ca;
  DynArray<char*, M> ca2 = ca;
  cout << ca2;
  if (ca2 == ca)
  {
    cout << "odinakivie" << endl;
  }
 
  return 0;
}
но также у меня есть варнинги
Code
1
[Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings]
в подобных местах
C++
1
  ca+"world!";
но вряд ли для этого нужна специализация
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
08.11.2022, 21:34
Ответы с готовыми решениями:

Написать шаблонный класс, который создает копию двумерного динамического массива произвольного типа
Написать шаблонный класс, который создает копию двумерного динамического массива произвольного типа. Предусмотреть операции копирования по...

Разработать шаблонный класс Stek на основе динамического массива размером 100
Разработать шаблонный класс Stek на основе динамического массива размером 100. Класс должен включать переменную-член top (вершина стека)....

Шаблонный класс со статическим методом вывода всех элементов переданного массива
Вот код, но что то не работает, выдает ошибку, помогите исправить #include &lt;iostream&gt; using namespace std; template...

28
 Аватар для SmallEvil
4086 / 2975 / 813
Регистрация: 29.06.2020
Сообщений: 11,000
09.11.2022, 20:45
Студворк — интернет-сервис помощи студентам
DrOffset, ну прям щами по мордами, иой французкий не то что бы плох,он никакой
Теперь мы точно говоорим об одном, только при всем этом, мне не понятна роль форума (для таких людей)?

Цитата Сообщение от DrOffset Посмотреть сообщение
что ему просто что-то тяжелее дается
p.s мне тоже очень много давалось тяжело
0
29 / 24 / 5
Регистрация: 15.10.2019
Сообщений: 268
09.11.2022, 21:10  [ТС]
DrOffset, иду к Вам на поклон
Сегодня спросил у преподавателя про специализацию, получил ответ, что нужно делать специализацию шаблона, а чтоб не было повтора кода, занести все общее в базовый класс, потом через заглушку сделать для реализации по умолчанию для инт, флоат и тд. И потом уж делать частичную специализацию для класса.

Я попытался воплотить услышанное.
Но получаю ошибку, которую не получается решить.
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#include <iostream>
#include <cstring>
 
using namespace std;
 
struct Vec2;
 
 
template <class T, int Nup>
class DynArrayBase {
 
protected:
    
  T* array;
  int Capacity;
  int length = 0;
 
  virtual void alloc(int newCapacity)
  {
    if (newCapacity <= Capacity) return;
    T* newArray = new T[newCapacity];
    for(int i = 0; i < newCapacity; ++i)
    {
      if (i < Capacity)
      {
        newArray[i] = array[i];
      }
      else
      {
        newArray[i] = 0;
      }
    }
    delete[] array;
    array = newArray;
    Capacity = newCapacity;
  }
 
  void malloc()
  {
    array = new T[Capacity];
    for(int i = 0; i < Capacity; ++i)
      array[i] = 0;
  }
 
public:
  DynArrayBase(int Capacity=0) : Capacity(Capacity)
  {
    malloc();
  }
  
  DynArrayBase()
  {
    Capacity=0;
    malloc();
  }
 
  DynArrayBase(DynArrayBase & otherObj)
  {
    cout<<endl<<"copy ctor!"<<endl;
    Capacity = otherObj.getCapacity();
    malloc();
    length = otherObj.getLength();
    for (int i = 0; i < length; ++i)
    {
      array[i] = otherObj[i];
    }
  }
 
  DynArrayBase & operator= (DynArrayBase & otherObj)
  {
    if ( &otherObj != this)
    {
      cout<<endl<<"oper prisvo!"<<endl;
      delete[] array;
      Capacity = otherObj.getCapacity();
      malloc();
      length = otherObj.getLength();
      for (int i = 0; i < length; ++i)
      {
        array[i] = otherObj[i];
      }
    }
    else
    {
      cout << "Была остановленна попытка самоприсваиванья. " << endl;
    }
        
    return *this;
  }
 
  ~DynArrayBase() { delete[] array; }
 
  T& operator[](int index) const
  {
    return array[index];
  }
 
  void reserve(int n) { alloc(Capacity + Nup); }
 
  virtual DynArrayBase & insert(T elem, int pos = -1)
  {
    pos = pos < 0 ? length : pos;
    //alloc(length + 1);
    if (Capacity < length + 1) { alloc(length + Nup); }
    for(int i = length - 2; i >= pos; ++i)
      array[i+1] = array[i];
    array[pos] = elem;
    length += 1;
    return *this; 
  }
 
  virtual DynArrayBase & operator+ (T elem)
  {
    insert(elem);
    return *this;
  }
 
  virtual DynArrayBase & remove(const T& elem, int pos = -1)
  {
    if(pos == -1)
    {
      for(int i = 0; i < length; ++i)
      {
        if(elem == array[i])
        {
          pos = i;
          break;
        }
      }
    }
    if(pos != -1 && pos < length)
    {
      for(int i = pos + 1; i < length; ++i)
      {
        array[i - 1] = array[i];
      }
      length -= 1;
    }
    return *this;
  }
 
  DynArrayBase & operator- (T elem)
  {
    remove(elem);
    return *this;
  } 
  
 
  void print();
  int getLength() const { return length; }
  int getCapacity() const { return Capacity; }
  bool isEmpty() const { return length == 0; }  
  
  bool operator== (DynArrayBase<T, Nup>& b)
  {
    if (this->getLength() == b.getLength())
    {
      for(int i=0; i < b.getLength(); ++i)
      {
        if (array[i] != b[i])
        {
          return false; break;
        }
      }
      return true;
    }
    else
    {
      return false;
    }
  }
    
  bool operator!= (DynArrayBase<T, Nup>& b)
  {
    if (this->getLength() == b.getLength())
    {
      for(int i=0; i < b.getLength(); ++i)
      {
        if (array[i] != b[i])
        {
          return true; break;
        }
      }
      return false;
    }
    else
    {
      return true;
    }
  } 
 
  
  
};
 
 
template <class T, int Nup> 
class DynArray: public DynArrayBase<T, Nup> {
 
};
 
 
template <int Nup>
class DynArray<char*, Nup> : public DynArrayBase<char*, Nup> {
 
 
  void alloc(int newCapacity) override
  {
    if (newCapacity <= this->Capacity) return;
    char** newArray = new char*[newCapacity];
    for(int i = 0; i < newCapacity; ++i)
    {
      if (i < this->Capacity)
      {
        strcpy(newArray[i], this->array[i]);
        //newArray[i] = array[i];
      }
      else
      {
        newArray[i] = 0;
      }
    }
    delete[] this->array;
    this->array = newArray;
    this->Capacity = newCapacity;
  }
 
 
public:
    
  DynArray<char*, Nup>(int Capacity=0)
  {
    this->Capacity = Capacity;
    this->malloc();
  }
 
    DynArray<char*, Nup>(const DynArray<char*, Nup> & otherObj)
  {
    cout<<endl<<"copy ctor chaar*!"<<endl;
    this->Capacity = otherObj.getCapacity();
    this->malloc();
    this->length = otherObj.getLength();
    for (int i = 0; i < this->length; ++i)
    {
        strcpy(this->array[i], otherObj[i]);
      //array[i] = otherObj[i];
    }
  }
 
  DynArray<char*, Nup> & operator= (const DynArrayBase<char*, Nup> & otherObj)
  {
    if ( &otherObj != this)
    {
      cout<<endl<<"oper prisvo chaar*!"<<endl;
      delete[] this->array;
      this->Capacity = otherObj.getCapacity();
      this->malloc();
      this->length = otherObj.getLength();
      for (int i = 0; i < this->length; ++i)
      {
        strcpy(this->array[i], otherObj[i]);
        //array[i] = otherObj[i];
      }
    }
    else
    {
      cout << "Была остановленна попытка самоприсваиванья. " << endl;
    }
        
    return *this;
  }
 
  ~DynArray() { }
 
 
  DynArray<char*, Nup> & insert(char* elem, int pos = -1) override
  {
    pos = pos < 0 ? this->length : pos;
    //alloc(length + 1);
    if (this->Capacity < this->length + 1) { alloc(this->length + Nup); }
    for(int i = this->length - 2; i >= pos; ++i)
        strcpy(this->array[i+1], this->array[i]);
      //array[i+1] = array[i];
    this->array[pos] = elem;
    this->length += 1;
    return *this; 
  }
 
DynArray<char*, Nup> & operator+ (char* elem) override
  {
    this->insert(elem);
    return *this;
  }
 
  DynArray<char*, Nup> & remove(const char*& elem, int pos = -1) override
  {
    if(pos == -1)
    {
      for(int i = 0; i < this->length; ++i)
      {
        if(elem == this->array[i])
        {
          pos = i;
          break;
        }
      }
    }
    if(pos != -1 && pos < this->length)
    {
      for(int i = pos + 1; i < this->length; ++i)
      {
        strcpy(this->array[i-1], this->array[i]);
        //array[i - 1] = array[i];
      }
      this->length -= 1;
    }
    return *this;
  }
  
  
  bool operator== (DynArrayBase<char*, Nup>& b)
  {
    if (this->getLength() == b.getLength())
    {
      for(int i=0; i < b.getLength(); ++i)
      {
        //if (array[i] != b[i])
        if (strcmp(this->array[i], b[i]) != 0)
        {
          return false; break;
        }
      }
      return true;
    }
    else
    {
      return false;
    }
  }
    
  bool operator!= (DynArrayBase<char*, Nup>& b)
  {
    if (this->getLength() == b.getLength())
    {
      for(int i=0; i < b.getLength(); ++i)
      {
        //if (array[i] != b[i])
        if (strcmp(this->array[i], b[i]) != 0)
        {
          return true; break;
        }
      }
      return false;
    }
    else
    {
      return true;
    }
  } 
 
  
  
};
 
 
template <class T, int Nup>
void DynArrayBase<T, Nup>::print()
{
  for(int i = 0; i < length; ++i)
    cout << array[i] << " ";
  cout << endl;
}
 
template <class T, int Nup>
ostream& operator<<(ostream & os, const DynArrayBase<T, Nup> & arr)
{
  for(int i = 0; i < arr.getLength(); ++i)
    os << arr[i] << " ";
  os << endl;
  return os;
}
 
 
/*template <int Nup>
void DynArrayBase<char*, Nup>::print()
{
  for(int i = 0; i < length; ++i)
    cout << array[i] << " ";
  cout << endl;
}*/
 
struct Vec2
{
  float x = 0, y = 0;
  
  Vec2(float a = 0) : x(a), y(a) {} 
  
  Vec2& operator=(float value)
  {
    x = y = value;
    return *this;
  }
  
  bool operator== (Vec2& b) const
  {
    if (x == b.x) {return true; }
    else { return false; }
  }
};
 
 
ostream& operator<<(ostream& os, const Vec2& vec)
{
  return os << " vec: " << vec.x << " " << vec.y;
}
 
int main(int argc, char** argv)
{
  system("chcp 1251");
  const int M = 3;
  cout << "Шаблон DynArrayBase<int>:" << endl;
  DynArray<int, M> intArray(10);
  intArray+1+2+3;
  intArray.print();
  DynArray<int, M> iAr2(10);
  iAr2+2+3+4+1;
  cout << iAr2;
  intArray = iAr2;
  cout << intArray;
 
 
 
  
  cout << "check char*" << endl;
  DynArray<char*, M> ca(1);
  /*ca+"hi";
  ca+"world!";  
  cout << ca;
  ca-"world!";
  cout << ca;
  DynArrayBase<char*, M> ca2 = ca;
  cout << ca2;
  if (ca2 == ca)
  {
    cout << "odinakivie" << endl;
  }
  ca+"new";
  cout << ca;
  cout << ca2;
  cout << "udalia" << endl;
  ca-"hi";
  cout << ca << ca2;*/
  char a[20];
    char b[20];
    strcpy(a,"hi");
    strcpy(b,"world!");
    ca+a;
    ca+b;
    cout << ca;
    strcpy(a,"***");
    strcpy(b,"***");
    
    cout << ca;
  
 
  return 0;
}
При создании экземпляра класса, получаю ошибки:
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
D:\Рабочий стол\laba5\main.cpp   In function 'int main(int, char**)':
422 31  D:\Рабочий стол\laba5\main.cpp   [Error] no matching function for call to 'DynArray<int, 3>::DynArray(int)'
422 31  D:\Рабочий стол\laba5\main.cpp   [Note] candidate is:
198 7   D:\Рабочий стол\laba5\main.cpp   [Note] DynArray<int, 3>::DynArray(DynArray<int, 3>&)
198 7   D:\Рабочий стол\laba5\main.cpp   [Note] no known conversion for argument 1 from 'int' to 'DynArray<int, 3>&'
425 27  D:\Рабочий стол\laba5\main.cpp   [Error] no matching function for call to 'DynArray<int, 3>::DynArray(int)'
425 27  D:\Рабочий стол\laba5\main.cpp   [Note] candidate is:
198 7   D:\Рабочий стол\laba5\main.cpp   [Note] DynArray<int, 3>::DynArray(DynArray<int, 3>&)
198 7   D:\Рабочий стол\laba5\main.cpp   [Note] no known conversion for argument 1 from 'int' to 'DynArray<int, 3>&'
D:\Рабочий стол\laba5\main.cpp   In instantiation of 'class DynArray<char*, 3>':
435 24  D:\Рабочий стол\laba5\main.cpp   required from here
295 26  D:\Рабочий стол\laba5\main.cpp   [Error] 'DynArray<char*, Nup>& DynArray<char*, Nup>::remove(const char*&, int) [with int Nup = 3]' marked override, but does not override
D:\Рабочий стол\laba5\main.cpp   In instantiation of 'DynArray<char*, Nup>::DynArray(int) [with int Nup = 3]':
435 26  D:\Рабочий стол\laba5\main.cpp   required from here
232 3   D:\Рабочий стол\laba5\main.cpp   [Error] call of overloaded 'DynArrayBase()' is ambiguous
232 3   D:\Рабочий стол\laba5\main.cpp   [Note] candidates are:
51  3   D:\Рабочий стол\laba5\main.cpp   [Note] DynArrayBase<T, Nup>::DynArrayBase() [with T = char*; int Nup = 3]
46  3   D:\Рабочий стол\laba5\main.cpp   [Note] DynArrayBase<T, Nup>::DynArrayBase(int) [with T = char*; int Nup = 3]
будто дело в конструкторе, но я его и так и сяк, а результата нет
0
 Аватар для SmallEvil
4086 / 2975 / 813
Регистрация: 29.06.2020
Сообщений: 11,000
09.11.2022, 21:21
Цитата Сообщение от billy121 Посмотреть сообщение
нужно делать специализацию шаблона, а чтоб не было повтора кода, занести все общее в базовый класс, потом через заглушку сделать для реализации по умолчанию для инт, флоат и тд. И потом уж делать частичную специализацию для класса.
для такого решения нужна сильная обоснованность. одних слов преподавателя мало.
"Я так вижу" , в программировании не работает. В таком режиме вы (преподаватель) упрется в стену, что нужно все переделывать. Все-все. Без вариантов.
0
29 / 24 / 5
Регистрация: 15.10.2019
Сообщений: 268
09.11.2022, 21:27  [ТС]
SmallEvil, возьмем на заметку, но в данный момент это не применимо
0
19501 / 10106 / 2461
Регистрация: 30.01.2014
Сообщений: 17,825
09.11.2022, 21:31
Цитата Сообщение от billy121 Посмотреть сообщение
C++
1
2
3
template <class T, int Nup> 
class DynArray: public DynArrayBase<T, Nup> {
};
C++
1
2
3
4
template <class T, int Nup>
class DynArray: public DynArrayBase<T, Nup> {
    using DynArrayBase<T, Nup>::DynArrayBase;
};
Цитата Сообщение от billy121 Посмотреть сообщение
C++
1
DynArray<char*, Nup> & remove(const char*& elem, int pos = -1) override
C++
1
DynArray<char*, Nup> & remove(char* const& elem, int pos = -1) override
Цитата Сообщение от billy121 Посмотреть сообщение
C++
1
2
3
4
5
  DynArrayBase()
  {
    Capacity=0;
    malloc();
  }
Удалить. Он дублирует конструктор с параметром по умолчанию.

Цитата Сообщение от billy121 Посмотреть сообщение
C++
1
2
3
4
5
6
  void malloc()
  {
    array = new T[Capacity];
    for(int i = 0; i < Capacity; ++i)
      array[i] = 0;
  }
C++
1
2
3
4
  void malloc()
  {
    array = new T[Capacity]{};
  }
Это только чтобы компилировалось. А так вижу там еще миллион ошибок. Кажется вы все испортили
Если это вам кажется проще, чем то, что я предложил я, то пожалуй мне нечего будет добавить к теме.
1
 Аватар для SmallEvil
4086 / 2975 / 813
Регистрация: 29.06.2020
Сообщений: 11,000
09.11.2022, 21:38
Цитата Сообщение от DrOffset Посмотреть сообщение
override
final
это никуда больше не поедет
0
09.11.2022, 21:50

Не по теме:

Цитата Сообщение от SmallEvil Посмотреть сообщение
это никуда больше не поедет
Может стоит взять за привычку цитировать код автора, а не мои цитаты кода автора? :)
Хотите что-то исправить у автора, пишите ему.
Я за его код не отвечаю.

0
29 / 24 / 5
Регистрация: 15.10.2019
Сообщений: 268
09.11.2022, 22:36  [ТС]
Цитата Сообщение от DrOffset Посмотреть сообщение
Кажется вы все испортили
да мне тоже так кажется
я внес ваши правки, а также понял, что не правильно делал копировал строковые элементы массива
пока переделал в alloc и insert

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
#include <iostream>
#include <cstring>
 
using namespace std;
 
struct Vec2;
 
 
template <class T, int Nup>
class DynArrayBase {
 
protected:
 
  T* array;
  int Capacity;
  int length = 0;
 
  virtual void alloc(int newCapacity)
  {
    if (newCapacity <= Capacity) return;
    T* newArray = new T[newCapacity];
    for(int i = 0; i < newCapacity; ++i)
    {
      if (i < Capacity)
      {
        newArray[i] = array[i];
      }
      else
      {
        newArray[i] = 0;
      }
    }
    delete[] array;
    array = newArray;
    Capacity = newCapacity;
  }
 
  void malloc()
  {
    array = new T[Capacity];
    //for(int i = 0; i < Capacity; ++i)
    //array[i] = 0;
  }
 
public:
  DynArrayBase (int Capacity=0) : Capacity(Capacity)
  {
    malloc();
  }
 
  //  DynArrayBase()
  //  {
  //    Capacity=0;
  //    malloc();
  //  }
 
  DynArrayBase(DynArrayBase & otherObj)
  {
    cout<<endl<<"copy ctor!"<<endl;
    Capacity = otherObj.getCapacity();
    malloc();
    length = otherObj.getLength();
    for (int i = 0; i < length; ++i)
    {
      array[i] = otherObj[i];
    }
  }
 
  DynArrayBase & operator= (DynArrayBase & otherObj)
  {
    if ( &otherObj != this)
    {
      cout<<endl<<"oper prisvo!"<<endl;
      delete[] array;
      Capacity = otherObj.getCapacity();
      malloc();
      length = otherObj.getLength();
      for (int i = 0; i < length; ++i)
      {
        array[i] = otherObj[i];
      }
    }
    else
    {
      cout << "Была остановленна попытка самоприсваиванья. " << endl;
    }
 
    return *this;
  }
 
  ~DynArrayBase() { delete[] array; }
 
  T& operator[](int index) const
  {
    return array[index];
  }
 
  void reserve(int n) { alloc(Capacity + Nup); }
 
  virtual DynArrayBase & insert(T elem, int pos = -1)
  {
    pos = pos < 0 ? length : pos;
    //alloc(length + 1);
    if (Capacity < length + 1) { alloc(length + Nup); }
    for(int i = length - 2; i >= pos; ++i)
      array[i+1] = array[i];
    array[pos] = elem;
    length += 1;
    return *this;
  }
 
  virtual DynArrayBase & operator+ (T elem)
  {
    insert(elem);
    return *this;
  }
 
  virtual DynArrayBase & remove(const T& elem, int pos = -1)
  {
    if(pos == -1)
    {
      for(int i = 0; i < length; ++i)
      {
        if(elem == array[i])
        {
          pos = i;
          break;
        }
      }
    }
    if(pos != -1 && pos < length)
    {
      for(int i = pos + 1; i < length; ++i)
      {
        array[i - 1] = array[i];
      }
      length -= 1;
    }
    return *this;
  }
 
  DynArrayBase & operator- (T elem)
  {
    remove(elem);
    return *this;
  }
 
 
  void print();
  int getLength() const { return length; }
  int getCapacity() const { return Capacity; }
  bool isEmpty() const { return length == 0; }
 
  virtual bool operator== (DynArrayBase<T, Nup>& b)
  {
    if (this->getLength() == b.getLength())
    {
      for(int i=0; i < b.getLength(); ++i)
      {
        if (array[i] != b[i])
        {
          return false; break;
        }
      }
      return true;
    }
    else
    {
      return false;
    }
  }
 
  virtual bool operator!= (DynArrayBase<T, Nup>& b)
  {
    if (this->getLength() == b.getLength())
    {
      for(int i=0; i < b.getLength(); ++i)
      {
        if (array[i] != b[i])
        {
          return true; break;
        }
      }
      return false;
    }
    else
    {
      return true;
    }
  }
 
 
 
};
 
 
template <class T, int Nup>
class DynArray: public DynArrayBase<T, Nup> {
  using DynArrayBase<T, Nup>::DynArrayBase;
};
 
 
template <int Nup>
class DynArray<char*, Nup> : public DynArrayBase<char*, Nup> {
 
 
  void alloc(int newCapacity) override
  {
    if (newCapacity <= this->Capacity) return;
    char** newArray = new char*[newCapacity];
    for(int i = 0; i < newCapacity; ++i)
    {
      if (i < this->Capacity)
      {
        newArray[i] = new char[strlen(this->array[i])];
 
        strcpy(newArray[i], this->array[i]);
        //newArray[i] = array[i];
      }
      else
      {
        newArray[i] = 0;
      }
    }
    delete[] this->array;
    this->array = newArray;
    this->Capacity = newCapacity;
  }
 
 
public:
 
  DynArray<char*, Nup>(int Capacity=0)
  {
    this->Capacity = Capacity;
    this->malloc();
  }
 
  DynArray<char*, Nup>(const DynArray<char*, Nup> & otherObj)
  {
    cout<<endl<<"copy ctor chaar*!"<<endl;
    this->Capacity = otherObj.getCapacity();
    this->malloc();
    this->length = otherObj.getLength();
    for (int i = 0; i < this->length; ++i)
    {
      strcpy(this->array[i], otherObj[i]);
      //array[i] = otherObj[i];
    }
  }
 
  DynArray<char*, Nup> & operator= (const DynArrayBase<char*, Nup> & otherObj)
  {
    if ( &otherObj != this)
    {
      cout<<endl<<"oper prisvo chaar*!"<<endl;
      delete[] this->array;
      this->Capacity = otherObj.getCapacity();
      this->malloc();
      this->length = otherObj.getLength();
      for (int i = 0; i < this->length; ++i)
      {
        strcpy(this->array[i], otherObj[i]);
        //array[i] = otherObj[i];
      }
    }
    else
    {
      cout << "Была остановленна попытка самоприсваиванья. " << endl;
    }
 
    return *this;
  }
 
  ~DynArray() { }
 
 
  DynArray<char*, Nup> & insert(char* elem, int pos = -1) override
  {
    pos = pos < 0 ? this->length : pos;
    //alloc(length + 1);
 
    if (this->Capacity < this->length + 1) { alloc(this->length + Nup); }
    for(int i = this->length - 2; i >= pos; ++i)
    {
      this->array[i+1] = new char[strlen(this->array[i])];
 
      strcpy(this->array[i+1], this->array[i]);
    }
 
 
      //strcpy(this->array[i+1], this->array[i]);
 
 
    //array[i+1] = array[i];
    //strcpy(this->array[pos], elem);
 
    this->array[pos] = new char[strlen(elem)];
    strcpy(this->array[pos], elem);
    //this->array[pos] = elem;
 
    //strcpy(this->array[pos-1],elem);
 
 
    this->length += 1;
    return *this;
  }
 
  DynArray<char*, Nup> & operator+ (char* elem) override
  {
    this->insert(elem);
    return *this;
  }
 
  DynArray<char*, Nup> & remove(char* const& elem, int pos = -1) override
  {
    if(pos == -1)
    {
      for(int i = 0; i < this->length; ++i)
      {
        if(elem == this->array[i])
        {
          pos = i;
          break;
        }
      }
    }
    if(pos != -1 && pos < this->length)
    {
      for(int i = pos + 1; i < this->length; ++i)
      {
        strcpy(this->array[i-1], this->array[i]);
        //array[i - 1] = array[i];
      }
      this->length -= 1;
    }
    return *this;
  }
 
 
  bool operator== (DynArrayBase<char*, Nup>& b) override
  {
    if (this->getLength() == b.getLength())
    {
      for(int i=0; i < b.getLength(); ++i)
      {
        //if (array[i] != b[i])
        if (strcmp(this->array[i], b[i]) != 0)
        {
          return false; break;
        }
      }
      return true;
    }
    else
    {
      return false;
    }
  }
 
  bool operator!= (DynArrayBase<char*, Nup>& b) override
  {
    if (this->getLength() == b.getLength())
    {
      for(int i=0; i < b.getLength(); ++i)
      {
        //if (array[i] != b[i])
        if (strcmp(this->array[i], b[i]) != 0)
        {
          return true; break;
        }
      }
      return false;
    }
    else
    {
      return true;
    }
  }
 
 
 
};
 
 
template <class T, int Nup>
void DynArrayBase<T, Nup>::print()
{
  for(int i = 0; i < length; ++i)
    cout << array[i] << " ";
  cout << endl;
}
 
template <class T, int Nup>
ostream& operator<<(ostream & os, const DynArrayBase<T, Nup> & arr)
{
  for(int i = 0; i < arr.getLength(); ++i)
    os << arr[i] << " ";
  os << endl;
  return os;
}
 
 
 
struct Vec2
{
  float x = 0, y = 0;
 
  Vec2(float a = 0) : x(a), y(a) {}
 
  Vec2& operator=(float value)
  {
    x = y = value;
    return *this;
  }
 
  bool operator== (Vec2& b) const
  {
    if (x == b.x) {return true; }
    else { return false; }
  }
};
 
 
ostream& operator<<(ostream& os, const Vec2& vec)
{
  return os << " vec: " << vec.x << " " << vec.y;
}
 
int main(int argc, char** argv)
{
  system("chcp 1251");
  const int M = 3;
  cout << "Шаблон DynArrayBase<int>:" << endl;
  DynArray<int, M> intArray(10);
  intArray+1+2+3;
  intArray.print();
  DynArray<int, M> iAr2(10);
  iAr2+2+3+4+1;
  cout << iAr2;
  intArray = iAr2;
  cout << intArray;
 
  cout << "check char*" << endl;
  DynArray<char*, M> ca(1);
  char a[20];
  char b[20];
  strcpy(a,"hi");
  strcpy(b,"world!");
  ca+a;
  ca+b;
  cout << ca;
  strcpy(a,"***");
  strcpy(b,"***");
 
  cout << ca;
 
 
  return 0;
}
Code
1
2
3
4
5
6
7
8
9
10
11
Шаблон DynArrayBase<int>:
1 2 3
2 3 4 1
 
oper prisvo!
2 3 4 1
check char*
hi world!
hi world!
 
Process finished with exit code 0
пока получил для данного случая удовлетворительный вариант, завтра проверю все остальные свои присвоения и затирания и будет уже чуть лучше, чем "испорчено" надеюсь
0
19501 / 10106 / 2461
Регистрация: 30.01.2014
Сообщений: 17,825
09.11.2022, 22:50
billy121, маленькая подсказка: виртуальность тут нафиг не нужна. У вас всё поведение статическое, решаемое через шаблоны.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
09.11.2022, 22:50

Пользовательський тип и шаблонный класс
У меня есть шаблонный клас(дек), он может обрабатывать стандартные типы данных, мне нужно чтобы он мог обработать пользователький тип: ...

Разработать шаблонный класс для нахождения заданных значений среди элементов одномерного массива
Задание. В соответствии с вариантом задания разработайте шаблон класса для решения предложенных задач. Подготовьте программу,...

Создать шаблонный класс для преобразования массивов из типа int в char.
Хелп как это сделать сиджу уже 2 дня и голову ломаю Создать шаблонный класс для преобразования массивов из типа int в char. нужно на с++

Вычисления суммы элементов массива с явной специализацией (тип char*)
Здравствуйте! Помогите найти сумму элементов массива с явной специализацией (тип char*)! Это должна быть шаблонная функция! ...

как переделать шаблонный класс-стек в шаблонный класс-очередь !
Есть класс-контейнер стек с сортировкой , а нужно класс-контейнер очередь ! как переделать ?? подскажите #include &quot;queue.h&quot; ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
29
Ответ Создать тему
Новые блоги и статьи
Оказывается, Unreal Engine позволяет качество на порядки выше, чем было в Lineedge
Etyuhibosecyu 05.07.2026
Жаль, конечно, что я не узнал об этом, пока Lineedge существовала, а то бы Noname2331 написал, что волки превращаются в пиксельную кашу, а я бы его попросил скачать какую-нибудь бриллиантовую или Pro. . .
Doom для терминала без стрельбы и монстров. 3D Raycasting на ascii.
dcc0 05.07.2026
Попросил нейронную сеть deepai. org написать рейкастинг 3D с библиотекой ncurses для Linux. Чтобы можно было ходить на стрелочки. Чтобы стены были отрисованы символами. Справилась. Первый вариант. . .
Установка статуса документа по условию
Maks 05.07.2026
Алгоритм из решения ниже реализован на нетиповом документе "НарядПутевка" разработанного в КА2. Задача: в табличной части "Материалы" документа при записи автоматически устанавливать статус. . .
Сезонность и суточность закисления почв
anaschu 04.07.2026
200 часов это все равно моловато. Есть ситуации, но нестандартные, когда смена происходит за 5 лет. Но обычно это 50 лет и более. Наверное, закисление почвы происходит сезонно в средней. . .
В чем ценность человеческого опыта в глобальном смысле?
kumehtar 03.07.2026
Возможно, ценность человека не в том, что он однажды достигает мудрости, а в том, что он становится носителем карты пути. Он знает не только истину, но и последовательность внутренних изменений,. . .
интеграция AnyLogic с самописным REST API и переход на Odoo
anaschu 03.07.2026
Успешная интеграция AnyLogic с самописным REST API и переход на промышленную Odoo WMS Сегодня проделал огромный путь от простой симуляции физических процессов до построения полноценной. . .
Поиск всех путей на ориентированном графе. Linux
dcc0 02.07.2026
Переработка старого кода из моей статьи. Через несколько переработок от PHP кода к C89 (надеюсь, 89). Но довольно запутанно получилось. Код для Linux. Но если убрать time и то, что с ним. . .
Сам себя обучал rest api
anaschu 02.07.2026
Педагогический лайфхак: Почему чистый REST API для ученика намного круче, чем готовые библиотеки Когда мы отказались от капризного JAR-файла AnyLogic и переписали код на стандартный HttpClient,. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru