Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.72/18: Рейтинг темы: голосов - 18, средняя оценка - 4.72
KeM6Pug}I{a
49 / 49 / 1
Регистрация: 23.08.2013
Сообщений: 202

Эксперты обобщенного программирования

25.08.2013, 21:37. Показов 3802. Ответов 40
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Прошу подсказать в чем тут ошибка ?
Вот часть когда куда указывают ошибки:
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
template < class ArrayList<T>> class Iterator
{
public:
    Itrator(ArrayList<T>&);
    bool hasNext();
    T &operator++();
    T &operator--();
    T &operator()(int);
    T &remove();
 
private:
    int seek;
    ArrayList<T> *obj;
}; 
 
template < class <ArrayList<T>> Iterator<ArrayList<T>> :: Iterator(ArrayList<T>& obj)
{
    this -> obj = &obj;
}
 
template < class <ArrayList<T>> bool Iterator< ArrayList<T>> :: hasNext()
{
    return seek < obj -> size();
}
 
template < class <ArrayList<T>> T &Iterator< ArrayList<T>>  :: operator++()
{
    return obj -> get(seek++);
}
 
template < class <ArrayList<T>> T &Iterator< ArrayList<T>> :: operator--()
{
    return obj -> get(--seek);
}
 
template < class <ArrayList<T>> T &Iterator <ArrayList<T>> :: operator()(int index)
{
    return obj -> get(index);
}
 
template < class <ArrayList<T>> T &Iterator <ArrayList<T>> :: remove()
{
    return obj -> remove(seek);
}
Ошибки:

Ошибка 38 error C2039: --: не является членом "`global namespace'" d:\vc c++ temp\arraylist\arraylist\arraylist.h 251 1 ArrayList

Ошибка 48 error C2039: (): не является членом "`global namespace'" d:\vc c++ temp\arraylist\arraylist\arraylist.h 256 1 ArrayList

Ошибка 34 error C2039: ++: не является членом "`global namespace'" d:\vc c++ temp\arraylist\arraylist\arraylist.h 246 1 ArrayList

Ошибка 24 error C2039: hasNext: не является членом "`global namespace'" d:\vc c++ temp\arraylist\arraylist\arraylist.h 241 1 ArrayList


Вот полный код программы :

(Проблема в самом конце)

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
#ifndef ArrayList_H
#define ArrayList_H
 
#include <stdexcept>
using std::runtime_error;
 
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::ostream;
 
 
struct IllegalModificationException : public runtime_error
{
public:
    IllegalModificationException() : runtime_error( "IllegalModificationException" ) {}
    IllegalModificationException(char * ch) : runtime_error( ch ) {}
};
 
 
template<class T> class ArrayList 
{
 
friend class Iterator < ArrayList<T>>;
friend ostream &operator<<(ostream &,ArrayList &);
 
public:
    explicit ArrayList(int = 10);
    virtual ~ArrayList();
    void add(T&);
    int size();
    T &get(int);
    T &get(int) const;
    bool contains(const T&);
    T &remove(int);
    Iterator < ArrayList<T>> &iterator();
    typedef Iterator< ArrayList <T>> *ListIterator;
 
 
private:
    int lenght;
    T ** mas;
    void setSize(int);
    void initMas();
    int seek;
    float shift;
    void removeHelper(T **temp,int index,int count,int count2);
};
 
template< class T > ArrayList < T > :: ArrayList(int d)
{
    setSize(d);
    shift = 2.0;
    seek = 0;
}
 
template< class T > ArrayList < T > :: ~ArrayList()
{
    delete [] mas;
}
 
template< class T > void ArrayList < T > :: initMas()
{
    mas = new T*[lenght];
}
 
template< class T > void ArrayList < T > :: setSize(int size)
{
    if(size > 0)
     lenght = size;
    else
       lenght = 10;
 
    initMas();
}
 
template< class T > int ArrayList < T > :: size()
{
    return seek;
}
 
template< class T> void ArrayList < T > :: add(T &obj)
{
 
    if(lenght == seek)
    {
        T ** temp = mas;
 
        lenght*= shift;
 
        mas = new T*[lenght];
 
        for(int i = 0; i < seek; i++)
        {
            mas[i] = temp[i];
        }
 
        delete [] temp;
 
    }
    mas[seek++] = &obj;
}
 
 
template < class T > T &ArrayList < T > :: get(int index) throw (IllegalModificationException)
{
    if(!(index > seek || index < 0))
    {
        return *mas[index];
    }
    else
    {
        throw IllegalModificationException("Illegal invoke");
    }
}
 
template < class T> T &ArrayList < T > :: get(int index) const throw (IllegalModificationException) 
{
    if(!(index > seek || index < 0))
    {
        return mas[index];
    }
    else
    {
        throw IllegalModificationException("Illegal invoke");
    }
}
 
template < class T > bool ArrayList < T > :: contains(const T &obj)
{
    for(int i = 0; i < seek; i++)
    {
        if(mas[i] == obj)
        {
            return true;
        }
    }
 
    return false;
}
 
template < class T > T &ArrayList < T > :: remove(int index) throw (IllegalModificationException)
{
    if(index > seek || index < 0)
    {
        throw IllegalModificationException();
    }
    else
    {
      T *tmp;
      T **temp = new T*[size()-1];
      for(int i = 0,j = 0; i < size()-1;)
      {
          if(j != index)
          {
              temp[i++] = mas[j++];
          }
          else
          {
              tmp = mas[j++];
              j++;
          }
      }
 
      for(int i = 0; i < size()-1;i++)
      {
          mas[i] = temp[i];
      }
 
      seek--; 
 
      delete [] temp;
 
      return tmp;  
    }
}
 
template < class T > void ArrayList < T > :: removeHelper(T **temp,int index,int count,int count2)
{
 
    if(count < (size()-1))
    {
        if(count2 != index)
        {
            temp[count] = mas[count2]; 
            cout << "temp[count++] = mas[count2++]; == " << count << " :: " << count2 << endl;
            count++;
            count2++;
        }
        else
        {
            count2++;
        }
        removeHelper(temp,index,count,count2);
 
    }
}
 
template < class T > ostream &operator<<(ostream &out,ArrayList<T> &d)
{
    for(int i = 0; i < d.size(); i++)
    {
        out << "["<< i << "]" << " :: " << *d.mas[i] << " ";
        if((i + 1) % 5 == 0)
        {
            out << endl;
        }
    }
 
    return out;
}
 
template < class T > Iterator<ArrayList<T>> &ArrayList < T > :: iterator()
{
    return new Iterator<ArrayList<T>>(this);
}
 
 
template < class ArrayList<T>> class Iterator
{
public:
    Itrator(ArrayList<T>&);
    bool hasNext();
    T &operator++();
    T &operator--();
    T &operator()(int);
    T &remove();
 
private:
    int seek;
    ArrayList<T> *obj;
}; 
 
template < class <ArrayList<T>> Iterator<ArrayList<T>> :: Iterator(ArrayList<T>& obj)
{
    this -> obj = &obj;
}
 
template < class <ArrayList<T>> bool Iterator< ArrayList<T>> :: hasNext()
{
    return seek < obj -> size();
}
 
template < class <ArrayList<T>> T &Iterator< ArrayList<T>>  :: operator++()
{
    return obj -> get(seek++);
}
 
template < class <ArrayList<T>> T &Iterator< ArrayList<T>> :: operator--()
{
    return obj -> get(--seek);
}
 
template < class <ArrayList<T>> T &Iterator <ArrayList<T>> :: operator()(int index)
{
    return obj -> get(index);
}
 
template < class <ArrayList<T>> T &Iterator <ArrayList<T>> :: remove()
{
    return obj -> remove(seek);
}
 
#endif
Добавлено через 6 минут
ПЫСЫ Класс ArrayList отлажен, нужно отладить только класс Itreator ... Вроде правильно я реализовал шаблон Iterator??
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
25.08.2013, 21:37
Ответы с готовыми решениями:

По ходу вирусняк. Эксперты помогайте!
По ходу поймал вирус. В общем, сам виноват, подозрения на скачиваемый файл были, и убедительные... (архив распаковывал) Позже провел...

Эксперты Pascal 'я, что не так?
Необходимо получить сумму из введенных чисел в файле, но программа даже не запускается. program number_5; var c, sum: integer; ...

Эксперты, просьба оценить сборку
День добрый, друзья. Решил я собрать системник, хочу обратиться за помощью, присмотрел уже пару вещей, постараюсь подробно изложить и жду...

40
 Аватар для Kastaneda
5232 / 3205 / 362
Регистрация: 12.12.2009
Сообщений: 8,143
Записей в блоге: 2
25.08.2013, 21:41
Цитата Сообщение от MbICJIuTeJIb_u3 Посмотреть сообщение
C++
1
template < class ArrayList<T>> class Iterator
И что такое Т в этой записи?
0
KeM6Pug}I{a
49 / 49 / 1
Регистрация: 23.08.2013
Сообщений: 202
25.08.2013, 21:58  [ТС]
Цитата Сообщение от Kastaneda Посмотреть сообщение
И что такое Т в этой записи?
это все java... А как правильно? Думаю теперь нужно просто объявить как
template <T> class Iterator{};... Но как быть с передачей ссылки в кон-ре ?

Добавлено через 2 минуты
Точней как мне сделать класс Iterator другом ArrayList?

friend class Iterator<T> ; ???

Добавлено через 6 минут
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
#ifndef ArrayList_H
#define ArrayList_H
 
#include <stdexcept>
using std::runtime_error;
 
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::ostream;
 
 
struct IllegalModificationException : public runtime_error
{
public:
    IllegalModificationException() : runtime_error( "IllegalModificationException" ) {}
    IllegalModificationException(char * ch) : runtime_error( ch ) {}
};
 
 
template<class T> class ArrayList 
{
 
friend class Iterator <T>;
friend ostream &operator<<(ostream &,ArrayList &);
 
public:
    explicit ArrayList(int = 10);
    virtual ~ArrayList();
    void add(T&);
    int size();
    T &get(int);
    T &get(int) const;
    bool contains(const T&);
    T &remove(int);
    Iterator <T> &iterator();
    typedef Iterator<T> *ListIterator;
 
 
private:
    int lenght;
    T ** mas;
    void setSize(int);
    void initMas();
    int seek;
    float shift;
    void removeHelper(T **temp,int index,int count,int count2);
};
 
template< class T > ArrayList < T > :: ArrayList(int d)
{
    setSize(d);
    shift = 2.0;
    seek = 0;
}
 
template< class T > ArrayList < T > :: ~ArrayList()
{
    delete [] mas;
}
 
template< class T > void ArrayList < T > :: initMas()
{
    mas = new T*[lenght];
}
 
template< class T > void ArrayList < T > :: setSize(int size)
{
    if(size > 0)
     lenght = size;
    else
       lenght = 10;
 
    initMas();
}
 
template< class T > int ArrayList < T > :: size()
{
    return seek;
}
 
template< class T> void ArrayList < T > :: add(T &obj)
{
 
    if(lenght == seek)
    {
        T ** temp = mas;
 
        lenght*= shift;
 
        mas = new T*[lenght];
 
        for(int i = 0; i < seek; i++)
        {
            mas[i] = temp[i];
        }
 
        delete [] temp;
 
    }
    mas[seek++] = &obj;
}
 
 
template < class T > T &ArrayList < T > :: get(int index) throw (IllegalModificationException)
{
    if(!(index > seek || index < 0))
    {
        return *mas[index];
    }
    else
    {
        throw IllegalModificationException("Illegal invoke");
    }
}
 
template < class T> T &ArrayList < T > :: get(int index) const throw (IllegalModificationException) 
{
    if(!(index > seek || index < 0))
    {
        return mas[index];
    }
    else
    {
        throw IllegalModificationException("Illegal invoke");
    }
}
 
template < class T > bool ArrayList < T > :: contains(const T &obj)
{
    for(int i = 0; i < seek; i++)
    {
        if(mas[i] == obj)
        {
            return true;
        }
    }
 
    return false;
}
 
template < class T > T &ArrayList < T > :: remove(int index) throw (IllegalModificationException)
{
    if(index > seek || index < 0)
    {
        throw IllegalModificationException();
    }
    else
    {
      T *tmp;
      T **temp = new T*[size()-1];
      for(int i = 0,j = 0; i < size()-1;)
      {
          if(j != index)
          {
              temp[i++] = mas[j++];
          }
          else
          {
              tmp = mas[j++];
              j++;
          }
      }
 
      for(int i = 0; i < size()-1;i++)
      {
          mas[i] = temp[i];
      }
 
      seek--; 
 
      delete [] temp;
 
      return tmp;  
    }
}
 
template < class T > void ArrayList < T > :: removeHelper(T **temp,int index,int count,int count2)
{
 
    if(count < (size()-1))
    {
        if(count2 != index)
        {
            temp[count] = mas[count2]; 
            cout << "temp[count++] = mas[count2++]; == " << count << " :: " << count2 << endl;
            count++;
            count2++;
        }
        else
        {
            count2++;
        }
        removeHelper(temp,index,count,count2);
 
    }
}
 
template < class T > ostream &operator<<(ostream &out,ArrayList<T> &d)
{
    for(int i = 0; i < d.size(); i++)
    {
        out << "["<< i << "]" << " :: " << *d.mas[i] << " ";
        if((i + 1) % 5 == 0)
        {
            out << endl;
        }
    }
 
    return out;
}
 
template < class T > Iterator<T> &ArrayList < T > :: iterator()
{
    return new Iterator<T>(this);
}
 
 
template < class T> class Iterator
{
public:
    Itrator(ArrayList<T>&);
    bool hasNext();
    T &operator++();
    T &operator--();
    T &operator()(int);
    T &remove();
 
private:
    int seek;
    ArrayList<T> *obj;
}; 
 
template < class <T> Iterator<T> :: Iterator(ArrayList<T>& obj)
{
    this -> obj = &obj;
}
 
template < class <T> bool Iterator<T> :: hasNext()
{
    return seek < obj -> size();
}
 
template < class <T> T &Iterator<T>  :: operator++()
{
    return obj -> get(seek++);
}
 
template < class <T> T &Iterator<T> :: operator--()
{
    return obj -> get(--seek);
}
 
template < class <T> T &Iterator <T> :: operator()(int index)
{
    return obj -> get(index);
}
 
template < class <T> T &Iterator <T> :: remove()
{
    return obj -> remove(seek);
}
 
#endif
Вот все поменял , но ошибки остались те же самые
0
 Аватар для Kastaneda
5232 / 3205 / 362
Регистрация: 12.12.2009
Сообщений: 8,143
Записей в блоге: 2
25.08.2013, 22:12
Ошибок так много, что даже не знаю с чего начать. И кода слишком много, поэтому сложно расказать сразу про все ошибки. Лучше делать так - писать маленький пример кода (строк 10 - 20) воспроизводящий одну из ошибок и выкладывать его. Тогда быстрей помогут.
2
KeM6Pug}I{a
49 / 49 / 1
Регистрация: 23.08.2013
Сообщений: 202
25.08.2013, 22:56  [ТС]
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
#ifndef ArrayList_H
#define ArrayList_H
 
#include <stdexcept>
using std::runtime_error;
 
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::ostream;
 
 
struct IllegalModificationException : public runtime_error
{
public:
    IllegalModificationException() : runtime_error( "IllegalModificationException" ) {}
    IllegalModificationException(char * ch) : runtime_error( ch ) {}
};
 
 
template<class T> class ArrayList 
{
 
friend class Iterator <T>;
friend ostream &operator<<(ostream &,ArrayList &);
 
public:
    explicit ArrayList(int = 10);
    virtual ~ArrayList();
    void add(T&);
    int size();
    T &get(int);
    T &get(int) const;
    bool contains(const T&);
    T &remove(int);
    Iterator <T> &iterator();
    typedef Iterator<T> *ListIterator;
 
 
private:
    int lenght;
    T ** mas;
    void setSize(int);
    void initMas();
    int seek;
    float shift;
    void removeHelper(T **temp,int index,int count,int count2);
};
 
template< class T > ArrayList < T > :: ArrayList(int d)
{
    setSize(d);
    shift = 2.0;
    seek = 0;
}
 
template< class T > ArrayList < T > :: ~ArrayList()
{
    delete [] mas;
}
 
template< class T > void ArrayList < T > :: initMas()
{
    mas = new T*[lenght];
}
 
template< class T > void ArrayList < T > :: setSize(int size)
{
    if(size > 0)
     lenght = size;
    else
       lenght = 10;
 
    initMas();
}
 
template< class T > int ArrayList < T > :: size()
{
    return seek;
}
 
template< class T> void ArrayList < T > :: add(T &obj)
{
 
    if(lenght == seek)
    {
        T ** temp = mas;
 
        lenght*= shift;
 
        mas = new T*[lenght];
 
        for(int i = 0; i < seek; i++)
        {
            mas[i] = temp[i];
        }
 
        delete [] temp;
 
    }
    mas[seek++] = &obj;
}
 
 
template < class T > T &ArrayList < T > :: get(int index) throw (IllegalModificationException)
{
    if(!(index > seek || index < 0))
    {
        return *mas[index];
    }
    else
    {
        throw IllegalModificationException("Illegal invoke");
    }
}
 
template < class T> T &ArrayList < T > :: get(int index) const throw (IllegalModificationException) 
{
    if(!(index > seek || index < 0))
    {
        return mas[index];
    }
    else
    {
        throw IllegalModificationException("Illegal invoke");
    }
}
 
template < class T > bool ArrayList < T > :: contains(const T &obj)
{
    for(int i = 0; i < seek; i++)
    {
        if(mas[i] == obj)
        {
            return true;
        }
    }
 
    return false;
}
 
template < class T > T &ArrayList < T > :: remove(int index) throw (IllegalModificationException)
{
    if(index > seek || index < 0)
    {
        throw IllegalModificationException();
    }
    else
    {
      T *tmp;
      T **temp = new T*[size()-1];
      for(int i = 0,j = 0; i < size()-1;)
      {
          if(j != index)
          {
              temp[i++] = mas[j++];
          }
          else
          {
              tmp = mas[j++];
              j++;
          }
      }
 
      for(int i = 0; i < size()-1;i++)
      {
          mas[i] = temp[i];
      }
 
      seek--; 
 
      delete [] temp;
 
      return tmp;  
    }
}
 
template < class T > void ArrayList < T > :: removeHelper(T **temp,int index,int count,int count2)
{
 
    if(count < (size()-1))
    {
        if(count2 != index)
        {
            temp[count] = mas[count2]; 
            cout << "temp[count++] = mas[count2++]; == " << count << " :: " << count2 << endl;
            count++;
            count2++;
        }
        else
        {
            count2++;
        }
        removeHelper(temp,index,count,count2);
 
    }
}
 
template < class T > ostream &operator<<(ostream &out,ArrayList<T> &d)
{
    for(int i = 0; i < d.size(); i++)
    {
        out << "["<< i << "]" << " :: " << *d.mas[i] << " ";
        if((i + 1) % 5 == 0)
        {
            out << endl;
        }
    }
 
    return out;
}
 
template < class T > Iterator<T> &ArrayList < T > :: iterator()
{
    return new Iterator<T>(this);
}
 
 
template < class T> class Iterator
{
public:
    Itrator(ArrayList<T>&);
    bool hasNext();
    T &operator++();
    T &operator--();
    T &operator()(int);
    T &remove();
 
private:
    int seek;
    ArrayList<T> *obj;
}; 
 
template < class T> Iterator<T> :: Iterator(ArrayList<T>& obj)
{
    this -> obj = &obj;
}
 
template < class T> bool Iterator<T> :: hasNext()
{
    return seek < obj -> size();
}
 
template < class T> T &Iterator<T>  :: operator++()
{
    return obj -> get(seek++);
}
 
template < class T> T &Iterator<T> :: operator--()
{
    return obj -> get(--seek);
}
 
template < class T> T &Iterator <T> :: operator()(int index)
{
    return obj -> get(index);
}
 
template < class T> T &Iterator <T> :: remove()
{
    return obj -> remove(seek);
}
 
#endif
Ссылается именно на iterator.
Ошибки:


Ошибка 38 error C2039: --: не является членом "`global namespace'" d:\vc c++ temp\arraylist\arraylist\arraylist.h 251 1 ArrayList

Ошибка 48 error C2039: (): не является членом "`global namespace'" d:\vc c++ temp\arraylist\arraylist\arraylist.h 256 1 ArrayList

Ошибка 34 error C2039: ++: не является членом "`global namespace'" d:\vc c++ temp\arraylist\arraylist\arraylist.h 246 1 ArrayList

Ошибка 24 error C2039: hasNext: не является членом "`global namespace'" d:\vc c++ temp\arraylist\arraylist\arraylist.h 241 1 ArrayList

Добавлено через 1 минуту
Цитата Сообщение от Kastaneda Посмотреть сообщение
Ошибок так много, что даже не знаю с чего начать. И кода слишком много, поэтому сложно расказать сразу про все ошибки. Лучше делать так - писать маленький пример кода (строк 10 - 20) воспроизводящий одну из ошибок и выкладывать его. Тогда быстрей помогут.
<< class T> эту ошибку исправил что ещё нетак ... Вроде читаю книгу все правильно...

Добавлено через 2 минуты
Вот отдельные куски кода:

ТУт ошибки:
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
template < class T> class Iterator
{
public:
    Itrator(ArrayList<T>&);
    bool hasNext();
    T &operator++();
    T &operator--();
    T &operator()(int);
    T &remove();
 
private:
    int seek;
    ArrayList<T> *obj;
}; 
 
template < class T> Iterator<T> :: Iterator(ArrayList<T>& obj)
{
    this -> obj = &obj;
}
 
template < class T> bool Iterator<T> :: hasNext()
{
    return seek < obj -> size();
}
 
template < class T> T &Iterator<T>  :: operator++()
{
    return obj -> get(seek++);
}
 
template < class T> T &Iterator<T> :: operator--()
{
    return obj -> get(--seek);
}
 
template < class T> T &Iterator <T> :: operator()(int index)
{
    return obj -> get(index);
}
 
template < class T> T &Iterator <T> :: remove()
{
    return obj -> remove(seek);
}
 
#endif
И тут объявление фриенда Itrator или typedef мне кажется (потому что не уверен что правильно написал..)

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
template<class T> class ArrayList 
{
 
friend class Iterator <T>;
friend ostream &operator<<(ostream &,ArrayList &);
 
public:
    explicit ArrayList(int = 10);
    virtual ~ArrayList();
    void add(T&);
    int size();
    T &get(int);
    T &get(int) const;
    bool contains(const T&);
    T &remove(int);
    Iterator <T> &iterator();
    typedef Iterator<T> *ListIterator;
 
 
private:
    int lenght;
    T ** mas;
    void setSize(int);
    void initMas();
    int seek;
    float shift;
    void removeHelper(T **temp,int index,int count,int count2);
};
Добавлено через 39 минут
Походу некто не знает в чем ошибка...
0
Комп_Оратор)
Эксперт по математике/физике
 Аватар для IGPIGP
9005 / 4706 / 630
Регистрация: 04.12.2011
Сообщений: 14,003
Записей в блоге: 16
25.08.2013, 23:34
Цитата Сообщение от MbICJIuTeJIb_u3 Посмотреть сообщение
Походу некто не знает в чем ошибка...
Пока некто молчит, я похулиганю. Это компилируется:
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
#include <iostream>
using namespace std;
template <typename T>
class Iterator_Arlst;
 
template <typename T>
class ArrayList 
{
public:
    explicit ArrayList(int = 10);
    virtual ~ArrayList();
    void add(T&);
    int size();
    T &get(int);
    T &get(int) const;
    bool contains(const T&);
    T &remove(int);
 Iterator_Arlst &iterator();
   typedef Iterator_Arlst *ListIterator;
 
 
private:
    int lenght;
    T ** mas;
    void setSize(int);
    void initMas();
    int seek;
    float shift;
    void removeHelper(T **temp,int index,int count,int count2);
};
 
template <typename T>
class Iterator_Arlst//так нет конфликта имён ))
{
public:
    Iterator_Arlst(ArrayList<T>& ob);
    bool hasNext();
    T &operator++();
    T &operator--();
    T &operator()(int);
    T &remove();
 
private:
    int seek;
    ArrayList<T> *obj;
};

А вообще, тут бы надо бы в раздел повыше.
1
KeM6Pug}I{a
49 / 49 / 1
Регистрация: 23.08.2013
Сообщений: 202
25.08.2013, 23:45  [ТС]
#!@!$! #!#$! !#!$!$! ###!@! Я уже всю книгу облазил б****** спасибо большое.. ща проверю...
0
25.08.2013, 23:49

Не по теме:

Цитата Сообщение от MbICJIuTeJIb_u3 Посмотреть сообщение
Я уже всю книгу облазил
интересно в каких книгах такое
Цитата Сообщение от MbICJIuTeJIb_u3 Посмотреть сообщение
C++
1
template < class <ArrayList<T>>
пишут?

0
KeM6Pug}I{a
49 / 49 / 1
Регистрация: 23.08.2013
Сообщений: 202
26.08.2013, 00:00  [ТС]
Цитата Сообщение от Jupiter Посмотреть сообщение
пишут?
В книгах по Java
Облазил я всю книгу после этого
template < class <ArrayList<T>>

Добавлено через 2 минуты
Все ровно не пойму почему тут нету типизации?
То есть почему мы не передаем вот этим объявления T?

Цитата Сообщение от IGPIGP Посмотреть сообщение
Iterator_Arlst &iterator();
* *typedef Iterator_Arlst *ListIterator;
Ведь мы должны вернуть не какой то там итератор , итератор который проходит по ArrayList<T>, а не ArrayList и возвращать должен вроде как Iterator<T>

И почему нету указание что Iterator друг?Если Мне нужно обращаться в закрытым элементам как я к ним обращусь?
0
Комп_Оратор)
Эксперт по математике/физике
 Аватар для IGPIGP
9005 / 4706 / 630
Регистрация: 04.12.2011
Сообщений: 14,003
Записей в блоге: 16
26.08.2013, 00:05
Цитата Сообщение от MbICJIuTeJIb_u3 Посмотреть сообщение
Ведь мы должны вернуть не какой то там итератор , итератор который проходит по ArrayList<T>,
Дык в опережающем объявлении он и объявлен как обобщенный. То есть в классе же ненужно аргументы шаблонов указывать (иначе перекроете общие аргументы в объявлении класса). Теперь в классе этот итератор и виден как:
Iterator_Arlst<T>
а пишется
Iterator_Arlst
за пределами: Iterator_Arlst<T>
Синтаксис... Враг не пройдет!

Не по теме:

Впрочем я могу тут и наговорить Вам. Интересно, что скажут люди, работающие с определением шаблонов плотно.:)

0
KeM6Pug}I{a
49 / 49 / 1
Регистрация: 23.08.2013
Сообщений: 202
26.08.2013, 00:16  [ТС]
Все ровно мне не понятно почему Iterator не объявлен как friend ...
Но вот тут ещё одна проблема:
C++
1
2
3
4
5
6
7
8
9
ArrayList<int> list1;
    ArrayList<int>:: ListIterator iter = list1.iterator();
 
    for(int i = 0; i < 5; i++)
    {
        list1.add(*new int(i));
    }
 
    while(iter -> hasNext()){}
Пишет что iter должен иметь тип указателя хотя я определил псевдоним типа так:

C++
1
typedef IteratorR *ListIterator;
В чем ошибка?

Вот полное объявление:

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
template <typename T> class IteratorR;
 
template<class T> class ArrayList 
{
 
//friend class IteratorR;
friend ostream &operator<<(ostream &,ArrayList &);
 
public:
    explicit ArrayList(int = 10);
    virtual ~ArrayList();
    void add(T&);
    int size();
    T &get(int);
    T &get(int) const;
    bool contains(const T&);
    T &remove(int);
    IteratorR &iterator();
    typedef IteratorR *ListIterator;
 
 
private:
    int lenght;
    T ** mas;
    void setSize(int);
    void initMas();
    int seek;
    float shift;
    void removeHelper(T **temp,int index,int count,int count2);
};
0
5499 / 4894 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
26.08.2013, 03:13
Кликните здесь для просмотра всего текста
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
template <typename T> class IteratorR;
 
template<class T> class ArrayList 
{
    
    //friend class IteratorR;
    friend ostream &operator<<(ostream &, ArrayList &);
 
public:
    explicit ArrayList(int = 10);
    virtual ~ArrayList();
    void add(T&);
    int size();
    T &get(int);
    T &get(int) const;
    bool contains(const T&);
    T &remove(int);
    IteratorR <T>* iterator();
    typedef IteratorR <T>* ListIterator;
 
 
private:
    int lenght;
    T ** mas;
    void setSize(int);
    void initMas();
    int seek;
    float shift;
    void removeHelper(T **temp,int index,int count,int count2);
};
 
template < class T> class IteratorR
{
public:
    IteratorR(T&);
    bool hasNext();
    T &operator++();
    T &operator--();
    T &operator()(int);
    T &remove();
 
private:
    int seek;
    ArrayList<T> *obj;
}; 
 
 
int main()
{
 
 ArrayList<int> list1;
 
ArrayList<int>::ListIterator iter = list1.iterator();
 
for(int i = 0; i < 5; i++)
{
    list1.add(*new int(i));
}
 
while(iter -> hasNext()){}
 
return 0;
 
}
2
KeM6Pug}I{a
49 / 49 / 1
Регистрация: 23.08.2013
Сообщений: 202
26.08.2013, 13:50  [ТС]
Цитата Сообщение от alsav22 Посмотреть сообщение
Кликните здесь для просмотра всего текста
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
template <typename T> class IteratorR;
 
template<class T> class ArrayList 
{
    
    //friend class IteratorR;
    friend ostream &operator<<(ostream &, ArrayList &);
 
public:
    explicit ArrayList(int = 10);
    virtual ~ArrayList();
    void add(T&);
    int size();
    T &get(int);
    T &get(int) const;
    bool contains(const T&);
    T &remove(int);
    IteratorR <T>* iterator();
    typedef IteratorR <T>* ListIterator;
 
 
private:
    int lenght;
    T ** mas;
    void setSize(int);
    void initMas();
    int seek;
    float shift;
    void removeHelper(T **temp,int index,int count,int count2);
};
 
template < class T> class IteratorR
{
public:
    IteratorR(T&);
    bool hasNext();
    T &operator++();
    T &operator--();
    T &operator()(int);
    T &remove();
 
private:
    int seek;
    ArrayList<T> *obj;
}; 
 
 
int main()
{
 
 ArrayList<int> list1;
 
ArrayList<int>::ListIterator iter = list1.iterator();
 
for(int i = 0; i < 5; i++)
{
    list1.add(*new int(i));
}
 
while(iter -> hasNext()){}
 
return 0;
 
}
А фриендом Iterator нужно объявлять ? Например если мне нужно что бы он получать доступ к private полям.

Добавлено через 14 минут
Теперь ошибка с получение итератора:
Ошибка в этом методе:
C++
1
2
3
4
template < class T > IteratorR<T> *ArrayList < T > :: iterator()
{
    return new IteratorR<T>(this);
}
Ошибки:
Ошибка 5 error C2244: ArrayList<T>::iterator: не удается сопоставить определение функции существующему объявлению d:\vc c++ temp\arraylist\arraylist\arraylist.h 219 1 ArrayList

Ошибка 4 error C2955: IteratorR: для использования класса шаблон требуется список аргументов шаблон d:\vc c++ temp\arraylist\arraylist\arraylist.h 216 1 ArrayList

Добавлено через 52 секунды
Обе ссылаются на этот метод... Что не так не пойму.

Добавлено через 51 секунду
Вот Определение:
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
template<class T> class ArrayList 
{
 
//friend class IteratorR;
friend ostream &operator<<(ostream &,ArrayList &);
 
public:
    explicit ArrayList(int = 10);
    virtual ~ArrayList();
    void add(T&);
    int size();
    T &get(int);
    T &get(int) const;
    bool contains(const T&);
    T &remove(int);
    IteratorR<T> *iterator();
    typedef IteratorR<T> *ListIterator;
 
 
private:
    int lenght;
    T ** mas;
    void setSize(int);
    void initMas();
    int seek;
    float shift;
    void removeHelper(T **temp,int index,int count,int count2);
};
0
5499 / 4894 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
26.08.2013, 14:22
Цитата Сообщение от MbICJIuTeJIb_u3 Посмотреть сообщение
А фриендом Iterator нужно объявлять ? Например если мне нужно что бы он получать доступ к private полям.
Получается, что шаблонный класс нельзя объявить как friend. Если не прав, пусть более знающие поправят.
Цитата Сообщение от MbICJIuTeJIb_u3 Посмотреть сообщение
Обе ссылаются на этот метод... Что не так не пойму.
Весь код выложите, чтобы можно было проверить.
0
What a waste!
 Аватар для gray_fox
1610 / 1302 / 180
Регистрация: 21.04.2012
Сообщений: 2,733
26.08.2013, 14:30
Цитата Сообщение от MbICJIuTeJIb_u3 Посмотреть сообщение
IteratorR<T>(this);
Нет такого конструктора. Есть
Цитата Сообщение от MbICJIuTeJIb_u3 Посмотреть сообщение
IteratorR(T&);
нужен
C++
1
IteratorR(ArrayList<T> *);
1
KeM6Pug}I{a
49 / 49 / 1
Регистрация: 23.08.2013
Сообщений: 202
26.08.2013, 14:52  [ТС]
Цитата Сообщение от gray_fox Посмотреть сообщение
Нет такого конструктора. Есть

нужен
C++
1
IteratorR(ArrayList<T> *);
Где вы у меня такой кон-ор увидели ?

C++
1
2
3
4
template < class T > IteratorR<T> *ArrayList < T > :: iterator()
{
    return new IteratorR<T>(this);
}
это не кон-ор..

Добавлено через 1 минуту
Цитата Сообщение от gray_fox Посмотреть сообщение
Нет такого конструктора. Есть

нужен
C++
1
IteratorR(ArrayList<T> *);
А все понял...спасибо
0
В астрале
Эксперт С++
 Аватар для ForEveR
8049 / 4806 / 655
Регистрация: 24.06.2010
Сообщений: 10,562
26.08.2013, 15:24
Цитата Сообщение от alsav22 Посмотреть сообщение
Получается, что шаблонный класс нельзя объявить как friend. Если не прав, пусть более знающие поправят.
Можно. Только для этого T

C++
1
friend class IteratorR<T>;
Для любого типа T

C++
1
2
template<typename U>
friend class IteratorR;
2
5499 / 4894 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
26.08.2013, 15:38
Цитата Сообщение от ForEveR Посмотреть сообщение
Можно. Только для этого T

C++
1
friend class IteratorR<T>;
В студии вот такой код не компилируется:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
 
template <class T>
class A
{
    friend class B <T>;
 
 
};
 
 
int main()
{
    
    system("pause");
    return 0;
}
Добавлено через 2 минуты
Или B нужно предварительно объявить как шаблон?
0
В астрале
Эксперт С++
 Аватар для ForEveR
8049 / 4806 / 655
Регистрация: 24.06.2010
Сообщений: 10,562
26.08.2013, 15:45
alsav22, Второе.
0
5499 / 4894 / 831
Регистрация: 04.06.2011
Сообщений: 13,587
26.08.2013, 16:38
Цитата Сообщение от ForEveR Посмотреть сообщение
alsav22, Второе.
А что тогда в классе объявляется как friend?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
26.08.2013, 16:38
Помогаю со студенческими работами здесь

Нужны эксперты в проверке кода
Вот нашкрябал код, но хотелось бы узнать у знающих и разбирающихся в этом людей: код можно уменьшить или так сойдёт? Все ADODB.Recordset...

Эксперты, где ошибка в TCP - пакете?
Добрый день всем. В поисках ответа забрел на Ваш форум. Кто сможет, подскажите пожалуйста куда копать. Пишу стек протоколов для...

Access 2000, Запрос, Помогите ув. Эксперты!!!
У меня есть 2 таблицы: 1)тбл_Заказчик_Инфо, содержит2 поля: -Заказчик_ИД -Заказчик_имя 2)тбл_родственники_инфо, содержит: ...

Синий экран смерти Приглашаются эксперты
Добрый день! Помогите пожалуйста. Стал выключаться комп. Да, старенький, Windows XP SP3/ Иногда просто гаснет монитор, а сам комп...

Эксперты сишки, для вас интересная задачка
Хэй хэй трусишники помогите студенту остаться со стипухой, а вам взамен предлагаю интересно потратить время или сотен на пив4ански, в общем...


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

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
Новые блоги и статьи
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Access
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru