Ошибка компилятора c2665

zayats80888

5987 / 3370 / 1373

Регистрация: 07.02.2019

Сообщений: 8,526

1

06.03.2019, 18:42. Показов 3103. Ответов 18

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте, уважаемые форумчане. Столкнулся с такой проблемой, делаю список с вложенными классами, класс работал нормально, пока не решил закольцевать перемещение по списку(до этого я просто выбрасывал исключения в операторах ++ и — на границах списка), добавив в Iterator поле-указатель на класс List. Теперь компилятор на константных методах begin() и end() выдает ошибку 2665, мол не может конвертировать параметры вызываемого конструктора. Порылся в интернете, попихал const и static_cast куда не нужно, ничего не вышло(тема для меня сложная).
P.S. Еще вопрос, можно ли реализацию методов моих классов переместить в отдельный *.cpp? Я пробовал, но линкер ругается, мол не видит реализацию методов класса Iterator.
Вот MyList.h:

Кликните здесь для просмотра всего текста

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
#include <memory>
#include <stdexcept>
//#300//класс список--------------------------------
 template<class Data> class List{
 public:
     List():_size(0),_head(0),_tail(0){}
     explicit List(const Data& dt);                 //#301//
     List(const List& lst);                         //#302//копирующий конструктор
     List& operator=(const List& lst);              //#303//копирующее присваивание
     ~List(){clear();}
 
     class Iterator;                                //#200//класс-член итератор
                                                    //перемещение по списку закольцовано
                                                    //признаком конца списка является 0
 
     Iterator begin();                              //#304//указывает на начало
     const Iterator begin() const;
     Iterator end();                                //#305//указывает на конец (фактически ссылается на 0)
     const Iterator end() const;
     Iterator insert(Iterator itr,const Data& dt);  //#306//вставка dt после элемента, на который установлен итератор itr
     Iterator erase(Iterator itr);                  //#307//удаление элемента, на который установлен итератор itr
 
     void push_back(const Data& dt);                //#308//вставка в конец списка
     void push_front(const Data& dt);               //#309//вставка в начало списка
     void pop_front();                              //#310//удаление начального элемента
     void pop_back();                               //#311//удаление конечного элемента
     void clear();                                  //#312//очистка списка
 
     typedef unsigned long size_type;
     size_type size() const {return _size;}         //размер списка
 
 private:
     class Node;                                    //#100//класс-член элемент списка
 
     size_type _size;
     Node* _head;
     Node* _tail;
 
     Node* create(const Data& dt,
                  Node* prev=0,
                  Node* next=0);                    //#313//динамическое создание элемента списка
 };
//#100//класс элемент списка------------------------
 template<class Data> class List<Data>::Node{
 public:
     Data _data;
     Node* _prev;
     Node* _next;
     Node(const Data& data, Node* prev=0, Node* next=0):_data(data),
                                                        _prev(prev),
                                                        _next(next){};
     ~Node(){std::cout<<'~'<<this<<std::endl;}
};
//#200//класс итератор------------------------------
template<class Data> class List<Data>::Iterator{
     Node* _curr;
     List* _owner;                                  //ссылается на экземпляр класса,
                                                    //которым был инициализирован
 public:
     friend class List;
     Iterator(Node* curr, List* owner): _curr(curr),
                                        _owner(owner){}
     Iterator& operator++();                        //#201//
     Iterator& operator--();                        //#202//
     bool operator==(const Iterator& itr) const;    //#203//
     bool operator!=(const Iterator& itr) const;    //#204//
 
     Data& operator*();                             //#205//разыменование
     //const Data& operator*() const;
 };
//--------------------------------------------------
//#200//реализация класса итератор------------------
//#201//--------------------------------------------
template<class Data>
typename List<Data>::Iterator& List<Data>::Iterator::operator++(){
    if (!_owner) throw std::out_of_range("Iterator::operator++()");
    if (_curr) _curr=_curr->_next;
    else _curr=_owner->_head;
    return *this;
}
//#202//--------------------------------------------
template<class Data>
typename List<Data>::Iterator& List<Data>::Iterator::operator--(){
    if (!_owner) throw std::out_of_range("Iterator::operator--()");
    if (_curr) _curr=_curr->_prev;
    else _curr=_owner->_tail;
    return *this;
}
//#203//--------------------------------------------
template<class Data>
bool List<Data>::Iterator::operator==(const typename List<Data>::Iterator& itr) const{
    return _curr==itr._curr;
}
//#204//--------------------------------------------
template<class Data>
bool List<Data>::Iterator::operator!=(const typename List<Data>::Iterator& itr) const{
    return !(*this==itr);
}
//#205//--------------------------------------------
template<class Data>
Data& List<Data>::Iterator::operator*(){
    if (_curr) return _curr->_data;
    else throw std::out_of_range("Iterator::operator*()");
}
//--------------------------------------------------
//#300//реализация класса список--------------------
//#301//--------------------------------------------
template<class Data>
List<Data>::List(const Data &dt){
    List();
    _head=_tail=create(dt);
    _size++;
}
//#302//--------------------------------------------
template<class Data>
List<Data>::List(const List<Data> &lst){
    Iterator source=lst.begin();
    while(source!=lst.end()){
        push_back(*source);
        ++source;
    }
}
//#303//--------------------------------------------
template<class Data>
List<Data>& List<Data>::operator =(const List<Data> &lst){
    Iterator source=lst.begin();
    Iterator dist=begin();
    while (source!=lst.end() && dist!=end()){
        *dist=*source;
        ++dist;
        ++source;
    }
    if (source==lst.end())
        while(dist!=end()) dist=erase(dist);
    else while(source!=lst.end()){
        push_back(*source);
        ++source;
    }
    return *this;
}
//#304//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::begin(){
    return Iterator(_head,this);
}
 
template<class Data>
const typename List<Data>::Iterator List<Data>::begin() const{
    return Iterator(_head,this);
}
//#305//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::end(){
    return Iterator(0,this);
}
 
template<class Data>
const typename List<Data>::Iterator List<Data>::end() const{
    return Iterator(0,this);
}
//#306//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::insert(typename List<Data>::Iterator itr,
                                                 const Data &dt){
    if (itr==end()) throw std::out_of_range("List<Data>::insert");
    Node* prev=itr._curr;
    ++itr;
    Node* succ=itr._curr;
    Node* curr=create(dt, prev, succ);
    if (prev) prev->_next=curr;
    else _head=curr;
    if (succ) succ->_prev=curr;
    else _tail=curr;
    _size++;
    return Iterator(curr);
}
//#307//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::erase(typename List<Data>::Iterator itr){
    if (itr==end()) throw std::out_of_range("List<Data>::erase");
    Node* curr=itr._curr;
    ++itr;
    if (curr->_next) curr->_next->_prev=curr->_prev;
    else _tail=curr->_prev;
    if (curr->_prev) curr->_prev->_next=curr->_next;
    else _head=curr->_next;
    delete curr;
    _size--;
    return itr;
}
//#308//--------------------------------------------
template<class Data>
void List<Data>::push_back(const Data &dt){
    Node* curr=create(dt, _tail);
    if(_tail) _tail->_next=curr;
    else _head=curr;
    _tail=curr;
    _size++;
}
//#309//--------------------------------------------
template<class Data>
void List<Data>::push_front(const Data &dt){
    Node* curr=create(dt, 0, _head);
    if (_head) _head->_prev=curr;
    else _tail=curr;
    _head=curr;
    _size++;
}
//#310//--------------------------------------------
template<class Data>
void List<Data>::pop_front(){
    if (!_head) return;
    Node* curr(_head);
    _head=curr->_next;
    _head->_prev=0;
    delete curr;
    _size--;
}
//#311//--------------------------------------------
template<class Data>
void List<Data>::pop_back(){
    if (!_tail) return;
    Node* curr(_tail);
    _tail=curr->_prev;
    _tail->_next=0;
    delete curr;
    _size--;
}
//#312//--------------------------------------------
template<class Data>
void List<Data>::clear(){
    while (_head){
        Node* curr(_head);
        _head=curr->_next;
        delete curr;
        _size--;
    }
}
//#312//--------------------------------------------
template<class Data>
typename List<Data>::Node* List<Data>::create(const Data &dt,
                                              typename List<Data>::Node *prev = 0,
                                              typename List<Data>::Node *next = 0){
    std::auto_ptr<Node> ptr(new Node(dt, prev, next));
    return ptr.release();
}



0



Параллельный Кот

1905 / 827 / 350

Регистрация: 25.03.2016

Сообщений: 2,045

06.03.2019, 19:40

2

Цитата
Сообщение от zayats80888
Посмотреть сообщение

Ошибка компилятора C2665

Неужели никакого более адекватного описания ошибки компилятор не показывает?

Код

source.cpp:242:28: error: redeclaration of ‘List<Data>::Node* List<Data>::create(const Data&, List<Data>::Node*, List<Data>::Node*)’ may not have default arguments [-fpermissive]
 typename List<Data>::Node* List<Data>::create(const Data &dt,
                            ^~~~~~~~~~

Оставьте значения по умолчанию только в объявлении.

Цитата
Сообщение от zayats80888
Посмотреть сообщение

можно ли реализацию методов моих классов переместить в отдельный *.cpp?

Вряд ли. У вас это не класс, а шаблон класса. Какую реализацию должен сделать компилятор в объектном файле без конкретизации типов? Есть способы заставить сделать реализацию для конечного набора типов, но тогда ваш список будет работать только с этим набором.



1



5987 / 3370 / 1373

Регистрация: 07.02.2019

Сообщений: 8,526

06.03.2019, 19:54

 [ТС]

3

Цитата
Сообщение от valen10
Посмотреть сообщение

Оставьте значения по умолчанию только в объявлении.

вы правы, только у меня VS2008, и с редекларацией значений по умолчанию все работало, а нагромождения остались когда я реализацию из отдельного *.cpp в *.h переносил, только у меня ошибка пока в другом месте. Вот что мне компилятор пишет:

Кликните здесь для просмотра всего текста

1>c:\users\arther\documents\visual studio 2008\projects\test 2\MyList.h(149) : error C2665: ‘List<Data>::Iterator::Iterator’ : none of the 2 overloads could convert all the argument types
1> with
1> [
1> Data=int
1> ]
1> c:\users\arther\documents\visual studio 2008\projects\test 2\MyList.h(61): could be ‘List<Data>::Iterator::Iterator(List<Data>::Node *,List<Data> *)’
1> with
1> [
1> Data=int
1> ]
1> while trying to match the argument list ‘(List<Data>::Node *const , const List<Data> *const )’
1> with
1> [
1> Data=int
1> ]
1> c:\users\arther\documents\visual studio 2008\projects\test 2\MyList.h(148) : while compiling class template member function ‘const List<Data>::Iterator List<Data>::begin(void) const’
1> with
1> [
1> Data=int
1> ]
1> c:\users\arther\documents\visual studio 2008\projects\test 2\MyList.h(109) : while compiling class template member function ‘List<Data>::List(const Data &)’
1> with
1> [
1> Data=int
1> ]
1> .\test2.cpp(9) : see reference to class template instantiation ‘List<Data>’ being compiled
1> with
1> [
1> Data=int
1> ]
1>c:\users\arther\documents\visual studio 2008\projects\test 2\MyList.h(159) : error C2665: ‘List<Data>::Iterator::Iterator’ : none of the 2 overloads could convert all the argument types
1> with
1> [
1> Data=int
1> ]
1> c:\users\arther\documents\visual studio 2008\projects\test 2\MyList.h(61): could be ‘List<Data>::Iterator::Iterator(List<Data>::Node *,List<Data> *)’
1> with
1> [
1> Data=int
1> ]
1> while trying to match the argument list ‘(int, const List<Data> *const )’
1> with
1> [
1> Data=int
1> ]
1> c:\users\arther\documents\visual studio 2008\projects\test 2\MyList.h(158) : while compiling class template member function ‘const List<Data>::Iterator List<Data>::end(void) const’
1> with
1> [
1> Data=int
1> ]



0



valen10

Параллельный Кот

1905 / 827 / 350

Регистрация: 25.03.2016

Сообщений: 2,045

06.03.2019, 20:15

4

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

C++
1
2
3
4
5
6
7
8
9
10
11
List<int> ll;
ll.push_back(1);
ll.push_back(2);
ll.push_back(3);
ll.push_back(4);
 
auto it = ll.begin();
while (it != ll.end()) {
    cout << *it << endl;
    ++it;
}

Еще обратите внимание на то, что auto_ptr считается deprecated.



1



IGPIGP

Комп_Оратор)

Эксперт по математике/физике

8916 / 4677 / 626

Регистрация: 04.12.2011

Сообщений: 13,912

Записей в блоге: 16

06.03.2019, 20:27

5

zayats80888,

Цитата
Сообщение от zayats80888
Посмотреть сообщение

до этого я просто выбрасывал исключения в операторах ++ и — на границах списка

Это скорее всего неверно. То есть, сделать то можно всё, но имеет смысл соблюдать семантику контейнеров уже существующих сегодня. Я о том, что итераторы не знают о том куда они указывают, как и указатели. Именно в этом и ценность. Начало и конец — собственность конкретного объекта контейнера и проверка — дело клиентского кода.

C++
1
if(iter_current == listOfWonders.end()) nobelievable() else do();

как видите доступ к end() через ссылку на экземпляр (listOfWonders). Бросать исключения в этом случае (их же ловить придётся) нет смысла, — пусть юзер отдувается, как всегда. А вот переход к кольцевому списку из-за этих проблем, это зря. Скрывая начало и конец вы не можете уйти от необходимости предоставления информации о целесообразности начала и конца итерации. Кроме того, вы уходите от возможности понять как оно реализовано в линейных структурах. То есть, end() возвращает значение итератора которое нельзя разыменовывать, но инкрементировать можно и его. Как и указатель.
И ещё. zayats80888, используйте алиасы для типов (есть же typedef и using). Если хотите — взгляните в мой блог
https://www.cyberforum.ru/blog… g4772.html
Там в архиве с исходником — заголовочники. И там есть самопальный итератор. Сделано не шибко красиво, но может и понравится. И наконец. Шаблоны можно разделить на хедер (h) и реализацию (cpp), только если в реализацию попадают нешаблонные методы. Игра не стоит свеч и так обычно не делают. Это потому, что фактически, реализации у шаблона нет. Она генерируется компилятором исходя из вызова или по предоставленной специализации. Поэтому, не делят. Компоновщику и так хватает работы.



1



zayats80888

5987 / 3370 / 1373

Регистрация: 07.02.2019

Сообщений: 8,526

06.03.2019, 20:28

 [ТС]

6

Цитата
Сообщение от valen10
Посмотреть сообщение

покажите пример использования,

да аналогичный вашему, просто тестирую

Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main(){
    List<int> lst;
    for (int i=0; i<10; ++i) lst.push_back(i);
    List<int>::Iterator iter=lst.begin();
    for (iter; iter!=lst.end(); ++iter) cout<<*iter<<endl;
    cout<< lst.size()<<endl;
    List<int> lst2(12);
    lst2.push_front(14);
    lst=lst2;
    for (iter=lst.begin(); iter!=lst.end(); ++iter) cout<<*iter<<endl;
    cout<< lst.size()<<endl;
    lst.clear();
    lst2.erase(lst2.begin());
    for (iter=lst2.begin(); iter!=lst2.end(); ++iter) cout<<*iter<<endl;
    system("pause");
    return 0;
}

А мусор может потому, что Iterator не имеет доступа к приватным членам класса List(не видит _head, _tail)?



0



Параллельный Кот

1905 / 827 / 350

Регистрация: 25.03.2016

Сообщений: 2,045

06.03.2019, 20:39

7

Цитата
Сообщение от zayats80888
Посмотреть сообщение

А мусор может потому, что Iterator не имеет доступа к приватным членам класса List(не видит _head, _tail)?

Нет, начало выводится нормально.

Мусор, потому что конец списка почему-то определяется неправильно

. Результат для кода, приведенного выше:

Ошибка компилятора C2665

Или это какая-то отладочная печать? Все, заметил ~Node(){std::cout<<'~'<<this<<std::endl;}, прошу прощения за ложную тревогу.



1



5987 / 3370 / 1373

Регистрация: 07.02.2019

Сообщений: 8,526

06.03.2019, 20:49

 [ТС]

8

Цитата
Сообщение от valen10
Посмотреть сообщение

компиляция без ошибок

А чем вы компилируете?



0



valen10

Параллельный Кот

1905 / 827 / 350

Регистрация: 25.03.2016

Сообщений: 2,045

06.03.2019, 21:52

9

Лучший ответ Сообщение было отмечено zayats80888 как решение

Решение

Цитата
Сообщение от zayats80888
Посмотреть сообщение

А чем вы компилируете?

gcc, но это не важно. Тот код везде нормально компилируется, ваш — нет. Одна и та же ошибка в строках 149 и 159:

Код

MyList.h:149:12: error: invalid conversion from ‘const List<int>*’ to ‘List<int>*’ [-fpermissive]
     return Iterator(_head,this);
            ^~~~~~~~~~~~~~~~~~~~

MyList.h:159:12: error: invalid conversion from ‘const List<int>*’ to ‘List<int>*’ [-fpermissive]
     return Iterator(0,this);
            ^~~~~~~~~~~~~~~~

Вызов происходит отсюда:

C++
126
127
    Iterator source=lst.begin();
    Iterator dist=begin();

Нельзя просто так взять и сделать константный указатель неконстантным. В STL, кажется, для такого случая используется отдельный итератор const_iterator. Как исправить, увы, не подскажу, ибо в такие дебри лазить еще не приходилось. Надеюсь, эта отсылка к строке с ошибкой наведет вас на верные мысли.



1



IGPIGP

Комп_Оратор)

Эксперт по математике/физике

8916 / 4677 / 626

Регистрация: 04.12.2011

Сообщений: 13,912

Записей в блоге: 16

06.03.2019, 22:15

10

zayats80888, у вас операции для итератора — набор странностей. Присваивание итератора не должно работать ни с чем кроме адреса. Не нужно бежать по всему контейнеру от начала. Вот этот код работает

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
#include <iostream>
#include <memory>
#include <stdexcept>
using namespace std;
 
//#300//класс список--------------------------------
 template<class Data> class List{
 public:
     List():_size(0),_head(0),_tail(0){}
     explicit List(const Data& dt);                 //#301//
     List(const List& lst);                         //#302//копирующий конструктор
     List& operator=(const List& lst);              //#303//копирующее присваивание
     ~List(){clear();}
 
     class Iterator;                                //#200//класс-член итератор
                                                    //перемещение по списку закольцовано
                                                    //признаком конца списка является 0
 
     Iterator begin();                              //#304//указывает на начало
     const Iterator begin() const;
     Iterator end();                                //#305//указывает на конец (фактически ссылается на 0)
     const Iterator end() const;
     Iterator insert(Iterator itr,const Data& dt);  //#306//вставка dt после элемента, на который установлен итератор itr
     Iterator erase(Iterator itr);                  //#307//удаление элемента, на который установлен итератор itr
 
     void push_back(const Data& dt);                //#308//вставка в конец списка
     void push_front(const Data& dt);               //#309//вставка в начало списка
     void pop_front();                              //#310//удаление начального элемента
     void pop_back();                               //#311//удаление конечного элемента
     void clear();                                  //#312//очистка списка
 
     typedef unsigned long size_type;
     size_type size() const {return _size;}         //размер списка
 
 private:
     class Node;                                    //#100//класс-член элемент списка
 
     size_type _size;
     Node* _head;
     Node* _tail;
 
     Node* create(const Data& dt,
                  Node* prev=0,
                  Node* next=0);                    //#313//динамическое создание элемента списка
 };
//#100//класс элемент списка------------------------
 template<class Data> class List<Data>::Node{
 public:
     Data _data;
     Node* _prev;
     Node* _next;
     Node(const Data& data, Node* prev=0, Node* next=0):_data(data),
                                                        _prev(prev),
                                                        _next(next){};
     ~Node(){std::cout<<'~'<<this<<std::endl;}
};
//#200//класс итератор------------------------------
template<class Data> class List<Data>::Iterator{
     Node* _curr;
     List* _owner;                                  //ссылается на экземпляр класса,
                                                    //которым был инициализирован
 public:
     friend class List;
     Iterator(Node* curr, List* owner): _curr(curr),
                                        _owner(owner){}
     Iterator& operator++();                        //#201//
     Iterator& operator--();                        //#202//
     bool operator==(const Iterator& itr) const;    //#203//
     bool operator!=(const Iterator& itr) const;    //#204//
 
     Data& operator*();                             //#205//разыменование
     //const Data& operator*() const;
 };
//--------------------------------------------------
//#200//реализация класса итератор------------------
//#201//--------------------------------------------
template<class Data>
typename List<Data>::Iterator& List<Data>::Iterator::operator++(){
    if (!_owner) throw std::out_of_range("Iterator::operator++()");
    if (_curr) _curr=_curr->_next;
    else _curr=_owner->_head;
    return *this;
}
//#202//--------------------------------------------
template<class Data>
typename List<Data>::Iterator& List<Data>::Iterator::operator--(){
    if (!_owner) throw std::out_of_range("Iterator::operator--()");
    if (_curr) _curr=_curr->_prev;
    else _curr=_owner->_tail;
    return *this;
}
//#203//--------------------------------------------
template<class Data>
bool List<Data>::Iterator::operator==(const typename List<Data>::Iterator& itr) const{
    return _curr==itr._curr;
}
//#204//--------------------------------------------
template<class Data>
bool List<Data>::Iterator::operator!=(const typename List<Data>::Iterator& itr) const{
    return !(*this==itr);
}
//#205//--------------------------------------------
template<class Data>
Data& List<Data>::Iterator::operator*(){
    if (_curr) return _curr->_data;
    else throw std::out_of_range("Iterator::operator*()");
}
//--------------------------------------------------
//#300//реализация класса список--------------------
//#301//--------------------------------------------
template<class Data>
List<Data>::List(const Data &dt){
    List();
    _head=_tail=create(dt);
    _size++;
}
//#302//--------------------------------------------
template<class Data>
List<Data>::List(const List<Data> &lst){
    Iterator source=lst.begin();
    while(source!=lst.end()){
        push_back(*source);
        ++source;
    }
}
//#303//--------------------------------------------
template<class Data>
List<Data>& List<Data>::operator =(const List<Data> &lst){
    Iterator source=lst.begin();
    Iterator dist=begin();
    while (source!=lst.end() && dist!=end()){
        *dist=*source;
        ++dist;
        ++source;
    }
    if (source==lst.end())
        while(dist!=end()) dist=erase(dist);
    else while(source!=lst.end()){
        push_back(*source);
        ++source;
    }
    return *this;
}
//#304//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::begin(){
    return Iterator(_head,this);
}
 
template<class Data>
const typename List<Data>::Iterator List<Data>::begin() const{
    return Iterator(_head,this);
}
//#305//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::end(){
    return Iterator(0,this);
}
 
template<class Data>
const typename List<Data>::Iterator List<Data>::end() const{
    return Iterator(0,this);
}
//#306//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::insert(typename List<Data>::Iterator itr,
                                                 const Data &dt){
    if (itr==end()) throw std::out_of_range("List<Data>::insert");
    Node* prev=itr._curr;
    ++itr;
    Node* succ=itr._curr;
    Node* curr=create(dt, prev, succ);
    if (prev) prev->_next=curr;
    else _head=curr;
    if (succ) succ->_prev=curr;
    else _tail=curr;
    _size++;
    return Iterator(curr);
}
//#307//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::erase(typename List<Data>::Iterator itr){
    if (itr==end()) throw std::out_of_range("List<Data>::erase");
    Node* curr=itr._curr;
    ++itr;
    if (curr->_next) curr->_next->_prev=curr->_prev;
    else _tail=curr->_prev;
    if (curr->_prev) curr->_prev->_next=curr->_next;
    else _head=curr->_next;
    delete curr;
    _size--;
    return itr;
}
//#308//--------------------------------------------
template<class Data>
void List<Data>::push_back(const Data &dt){
    Node* curr=create(dt, _tail);
    if(_tail) _tail->_next=curr;
    else _head=curr;
    _tail=curr;
    _size++;
}
//#309//--------------------------------------------
template<class Data>
void List<Data>::push_front(const Data &dt){
    Node* curr=create(dt, 0, _head);
    if (_head) _head->_prev=curr;
    else _tail=curr;
    _head=curr;
    _size++;
}
//#310//--------------------------------------------
template<class Data>
void List<Data>::pop_front(){
    if (!_head) return;
    Node* curr(_head);
    _head=curr->_next;
    _head->_prev=0;
    delete curr;
    _size--;
}
//#311//--------------------------------------------
template<class Data>
void List<Data>::pop_back(){
    if (!_tail) return;
    Node* curr(_tail);
    _tail=curr->_prev;
    _tail->_next=0;
    delete curr;
    _size--;
}
//#312//--------------------------------------------
template<class Data>
void List<Data>::clear(){
    while (_head){
        Node* curr(_head);
        _head=curr->_next;
        delete curr;
        _size--;
    }
}
//#312//--------------------------------------------
template<class Data>
typename List<Data>::Node* List<Data>::create(const Data &dt,
                                              typename List<Data>::Node *prev ,
                                              typename List<Data>::Node *next){
    std::auto_ptr<Node> ptr(new Node(dt, prev, next));
    return ptr.release();
}
 
int main(int argc, char **argv)
{
List<int> lst;
lst.push_back(4);
lst.push_back(5);
List<int>::Iterator it_beg=lst.begin(), it_end=lst.end();
while(it_beg!=it_end){
    cout<<*(it_beg)<<' ';
    ++it_beg;
}
cin.get();
return 0;
}

печатая в конце какие-то адреса. Нельзя понять где у вас те сообщения компилятора потому что:

Цитата
Сообщение от valen10
Посмотреть сообщение

покажите пример использования, на котором возникает эта ошибка, чтобы его можно было скомпилировать.



1



valen10

Параллельный Кот

1905 / 827 / 350

Регистрация: 25.03.2016

Сообщений: 2,045

06.03.2019, 22:28

11

IGPIGP, замените main() на этот:

C++
1
2
3
4
5
6
7
8
int main(int argc, char **argv)
{
    List<int> lst;
    List<int> lst2;
    lst2 = lst;
    
    return 0;
}

Получите ошибку из поста #9. Начинается всё с оператора копирования и приводит в код создания константного итератора, где что-то не так.



1



zayats80888

5987 / 3370 / 1373

Регистрация: 07.02.2019

Сообщений: 8,526

06.03.2019, 22:52

 [ТС]

12

Цитата
Сообщение от IGPIGP
Посмотреть сообщение

у вас операции для итератора — набор странностей.

Ну я тока учусь, куда же без них

Цитата
Сообщение от IGPIGP
Посмотреть сообщение

Присваивание итератора не должно работать ни с чем кроме адреса.

Это вы наверное про копирующее присваивание класса List. Я там через итераторы реализовать решил. И ошибка похоже именно там.

Цитата
Сообщение от valen10
Посмотреть сообщение

Нельзя просто так взять и сделать константный указатель неконстантным.

Да, похоже в этом и ошибка. В любом случае, спасибо, за потраченное на помощь время. Полезу изучать матчасть.

Добавлено через 5 секунд

Цитата
Сообщение от valen10
Посмотреть сообщение

замените main() на этот:

забыл сказать, что у меня конструктор по умолчанию не реализован для итератора, так что

C++
1
 List<int> lst;

не прокатывает, но это ошибка другого рода.
Косяк похоже в копировании списка, как вы выше заметили.



0



IGPIGP

Комп_Оратор)

Эксперт по математике/физике

8916 / 4677 / 626

Регистрация: 04.12.2011

Сообщений: 13,912

Записей в блоге: 16

06.03.2019, 23:11

13

Лучший ответ Сообщение было отмечено zayats80888 как решение

Решение

Цитата
Сообщение от valen10
Посмотреть сообщение

Получите ошибку из поста #9. Начинается всё с оператора копирования и приводит в код создания константного итератора, где что-то не так.

Спасибо, — посмотрю. cv в контейнерах это вообще морока, так как нельзя инстанцироваться на <const T>

Добавлено через 17 минут

Цитата
Сообщение от valen10
Посмотреть сообщение

Начинается всё с оператора копирования и приводит в код создания константного итератора, где что-то не так.

Метод объявлен константным потому-что, я думаю.
Так и есть:

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
#include <iostream>
#include <memory>
#include <stdexcept>
using namespace std;
 
//#300//класс список--------------------------------
 template<class Data> class List{
 public:
     List():_size(0),_head(0),_tail(0){}
     explicit List(const Data& dt);                 //#301//
     List(const List& lst);                         //#302//копирующий конструктор
     List& operator=( List& lst);              //#303//копирующее присваивание
     ~List(){clear();}
 
     class Iterator;                                //#200//класс-член итератор
                                                    //перемещение по списку закольцовано
                                                    //признаком конца списка является 0
 
     Iterator begin();                              //#304//указывает на начало
     //const Iterator begin() const;
     Iterator end();                                //#305//указывает на конец (фактически ссылается на 0)
     //const Iterator end() const;
     Iterator insert(Iterator itr,const Data& dt);  //#306//вставка dt после элемента, на который установлен итератор itr
     Iterator erase(Iterator itr);                  //#307//удаление элемента, на который установлен итератор itr
 
     void push_back(const Data& dt);                //#308//вставка в конец списка
     void push_front(const Data& dt);               //#309//вставка в начало списка
     void pop_front();                              //#310//удаление начального элемента
     void pop_back();                               //#311//удаление конечного элемента
     void clear();                                  //#312//очистка списка
 
     typedef unsigned long size_type;
     size_type size() const {return _size;}         //размер списка
 
 private:
     class Node;                                    //#100//класс-член элемент списка
 
     size_type _size;
     Node* _head;
     Node* _tail;
 
     Node* create(const Data& dt,
                  Node* prev=0,
                  Node* next=0);                    //#313//динамическое создание элемента списка
 };
//#100//класс элемент списка------------------------
 template<class Data> class List<Data>::Node{
 public:
     Data _data;
     Node* _prev;
     Node* _next;
     Node(const Data& data, Node* prev=0, Node* next=0):_data(data),
                                                        _prev(prev),
                                                        _next(next){};
     ~Node(){std::cout<<'~'<<this<<std::endl;}
};
//#200//класс итератор------------------------------
template<class Data> class List<Data>::Iterator{
     Node* _curr;
     List* _owner;                                  //ссылается на экземпляр класса,
                                                    //которым был инициализирован
 public:
     friend class List;
     Iterator( Node* curr,  List* owner): _curr(curr),
                                        _owner(owner){}
 
 
     Iterator& operator++();                        //#201//
     Iterator& operator--();                        //#202//
     bool operator==(const Iterator& itr) const;    //#203//
     bool operator!=(const Iterator& itr) const;    //#204//
 
     Data& operator*();                             //#205//разыменование
     //const Data& operator*() const;
 };
//--------------------------------------------------
//#200//реализация класса итератор------------------
//#201//--------------------------------------------
template<class Data>
typename List<Data>::Iterator& List<Data>::Iterator::operator++(){
    if (!_owner) throw std::out_of_range("Iterator::operator++()");
    if (_curr) _curr=_curr->_next;
    else _curr=_owner->_head;
    return *this;
}
//#202//--------------------------------------------
template<class Data>
typename List<Data>::Iterator& List<Data>::Iterator::operator--(){
    if (!_owner) throw std::out_of_range("Iterator::operator--()");
    if (_curr) _curr=_curr->_prev;
    else _curr=_owner->_tail;
    return *this;
}
//#203//--------------------------------------------
template<class Data>
bool List<Data>::Iterator::operator==(const typename List<Data>::Iterator& itr) const{
    return _curr==itr._curr;
}
//#204//--------------------------------------------
template<class Data>
bool List<Data>::Iterator::operator!=(const typename List<Data>::Iterator& itr) const{
    return !(*this==itr);
}
//#205//--------------------------------------------
template<class Data>
Data& List<Data>::Iterator::operator*(){
    if (_curr) return _curr->_data;
    else throw std::out_of_range("Iterator::operator*()");
}
//--------------------------------------------------
//#300//реализация класса список--------------------
//#301//--------------------------------------------
template<class Data>
List<Data>::List(const Data &dt){
    List();
    _head=_tail=create(dt);
    _size++;
}
//#302//--------------------------------------------
template<class Data>
List<Data>::List(const List<Data> &lst){
    Iterator source=lst.begin();
    while(source!=lst.end()){
        push_back(*source);
        ++source;
    }
}
//#303//--------------------------------------------
template<class Data>
List<Data>& List<Data>::operator =(List<Data> &lst){
    Iterator source=lst.begin();
    Iterator dist=begin();
    while (source!=lst.end() && dist!=end()){
        *dist=*source;
        ++dist;
        ++source;
    }
    if (source==lst.end())
        while(dist!=end()) dist=erase(dist);
    else while(source!=lst.end()){
        push_back(*source);
        ++source;
    }
    return *this;
}
//#304//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::begin(){
    return Iterator(_head,this);
}
/*
template<class Data>
const typename List<Data>::Iterator List<Data>::begin() const{
    return Iterator(_head,this);
}*/
 
//#305//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::end(){
    return Iterator(0,this);
}
/*
template<class Data>
const typename List<Data>::Iterator List<Data>::end() const{
    return Iterator(0,this);
}
*/
//#306//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::insert(typename List<Data>::Iterator itr,
                                                 const Data &dt){
    if (itr==end()) throw std::out_of_range("List<Data>::insert");
    Node* prev=itr._curr;
    ++itr;
    Node* succ=itr._curr;
    Node* curr=create(dt, prev, succ);
    if (prev) prev->_next=curr;
    else _head=curr;
    if (succ) succ->_prev=curr;
    else _tail=curr;
    _size++;
    return Iterator(curr);
}
//#307//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::erase(typename List<Data>::Iterator itr){
    if (itr==end()) throw std::out_of_range("List<Data>::erase");
    Node* curr=itr._curr;
    ++itr;
    if (curr->_next) curr->_next->_prev=curr->_prev;
    else _tail=curr->_prev;
    if (curr->_prev) curr->_prev->_next=curr->_next;
    else _head=curr->_next;
    delete curr;
    _size--;
    return itr;
}
//#308//--------------------------------------------
template<class Data>
void List<Data>::push_back(const Data &dt){
    Node* curr=create(dt, _tail);
    if(_tail) _tail->_next=curr;
    else _head=curr;
    _tail=curr;
    _size++;
}
//#309//--------------------------------------------
template<class Data>
void List<Data>::push_front(const Data &dt){
    Node* curr=create(dt, 0, _head);
    if (_head) _head->_prev=curr;
    else _tail=curr;
    _head=curr;
    _size++;
}
//#310//--------------------------------------------
template<class Data>
void List<Data>::pop_front(){
    if (!_head) return;
    Node* curr(_head);
    _head=curr->_next;
    _head->_prev=0;
    delete curr;
    _size--;
}
//#311//--------------------------------------------
template<class Data>
void List<Data>::pop_back(){
    if (!_tail) return;
    Node* curr(_tail);
    _tail=curr->_prev;
    _tail->_next=0;
    delete curr;
    _size--;
}
//#312//--------------------------------------------
template<class Data>
void List<Data>::clear(){
    while (_head){
        Node* curr(_head);
        _head=curr->_next;
        delete curr;
        _size--;
    }
}
//#312//--------------------------------------------
template<class Data>
typename List<Data>::Node* List<Data>::create(const Data &dt,
                                              typename List<Data>::Node *prev ,
                                              typename List<Data>::Node *next){
    std::auto_ptr<Node> ptr(new Node(dt, prev, next));
    return ptr.release();
}
 
int main(int argc, char **argv)
{
List<int> lst;
lst.push_back(4);
lst.push_back(5);
List<int>::Iterator it_beg=lst.begin(), it_end=lst.end();
while(it_beg!=it_end){
    cout<<*(it_beg)<<' ';
    ++it_beg;
}
 
    List<int> lst2;
    lst2 = lst;
 
cin.get();
return 0;
}

Я просто убрал константность даже в конструкторе копий. Нельзя предоставить указатель на внутренности (неконстантный) и ждать что компилятор позволит доступ внутрь константного объекта (rvalue если точнее). Вообще — много косяков это не то слово. Но с другой стороны так легче учиться может быть. Кому-как…



1



5987 / 3370 / 1373

Регистрация: 07.02.2019

Сообщений: 8,526

06.03.2019, 23:15

 [ТС]

14

Если в итераторе убрать ссылку на список, и следовательно не прередавать this в константных методах begin() и end(), то копирование работает. Только я не знаю, как реализовать Iterator—, если он установлен на end(), не создавая «пустой» экземпляр Node для идентификации этого конца.



0



Комп_Оратор)

Эксперт по математике/физике

8916 / 4677 / 626

Регистрация: 04.12.2011

Сообщений: 13,912

Записей в блоге: 16

06.03.2019, 23:44

15

Цитата
Сообщение от zayats80888
Посмотреть сообщение

Если в итераторе убрать ссылку на список

Её там быть не должно. Итератор не знает о контейнере (конкретном объекте).

Цитата
Сообщение от zayats80888
Посмотреть сообщение

Только я не знаю, как реализовать Iterator—, если он установлен на end()

Можно и создать. Но вообще, возможность декрементировать end() это поиск неприятностей. Где это может быть необходимо? zayats80888, даже при реализации reverse_iterator вам нужно отыскать последний фактический итератор (тот что перед end()), и это делается пробежкой до end() при наличии ещё одной переменной навродь iter_prev — предыдущий по отношению к переменной итерации iter_current != passed_list_to_serve.end()

Добавлено через 20 минут

Цитата
Сообщение от IGPIGP
Посмотреть сообщение

Её там быть не должно. Итератор не знает о контейнере (конкретном объекте).

тут я сморозил чушь. Давно не писал чего-то похожего.



1



zayats80888

5987 / 3370 / 1373

Регистрация: 07.02.2019

Сообщений: 8,526

07.03.2019, 18:53

 [ТС]

16

Почесав репу, удалось решить исходную проблему, просто объявив поле _owner и параметр конструктора итератора как указатели на константный объект:

Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//#200//класс итератор------------------------------
template<class Data> class List<Data>::Iterator{
     Node* _curr;
     const List* _owner;                            //ссылается на экземпляр класса,
                                                    //которым был инициализирован
 public:
     friend class List;
     Iterator(Node* curr=0, const List* owner=0): _curr(curr),
                                                  _owner(owner){}
     Iterator& operator++();                        //#201//
     Iterator& operator--();                        //#202//
     bool operator==(const Iterator& itr) const;    //#203//
     bool operator!=(const Iterator& itr) const;    //#204//
 
     Data& operator*();                             //#205//разыменование
     const Data& operator*() const;
 };

И все же, следуя вашим советам, я пересмотрю функционал итератора. Всем спасибо за помощь.



0



Комп_Оратор)

Эксперт по математике/физике

8916 / 4677 / 626

Регистрация: 04.12.2011

Сообщений: 13,912

Записей в блоге: 16

08.03.2019, 01:41

17

Цитата
Сообщение от zayats80888
Посмотреть сообщение

просто объявив поле _owner

Беда в том, что вы получите итератор через который сможете выполнять только константные операции. Например, вывод в поток. Но вы же наверняка планируете и писать через итератор?

Добавлено через 15 минут
zayats80888, теперь понимаете почему нет cv для typename list<T>::iterator, а есть аж целый const_iterator. Может тут поступить так же? А вот как решить без повторения кода (класс же будет другой) — стоит подумать. Отнаследовать оба от общего предка? Пойду спать. А то понапишу на ночь глядя.



1



zayats80888

5987 / 3370 / 1373

Регистрация: 07.02.2019

Сообщений: 8,526

08.03.2019, 03:29

 [ТС]

18

Цитата
Сообщение от IGPIGP
Посмотреть сообщение

Беда в том, что вы получите итератор через который сможете выполнять только константные операции.

Почему же? Поле _owner не используется для доступа к самим данным, хранящимся в контейнере. Как писал в топике, я ввел его только для «удобной» навигации по списку, т. е. если итератор установлен на end(), оператор ++ устанавливает его на begin(), а — на последний действительный элемент. Для разыменования используется поле _curr.
Беда как раз в том, что с помощью этого итератора можно менять данные константного контейнера.
Как я догадываюсь(я не знаю, я только изучаю это тему) const_iterator и нужен для того, что бы такого не происходило.
Ниже пример для моего класса, где через итератор переписываются данные константного списка:
Исправленный MyList.h:

Кликните здесь для просмотра всего текста

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
#include <memory>
#include <stdexcept>
//#300//класс список--------------------------------
 template<class Data> class List{
 public:
     List():_size(0),_head(0),_tail(0){}
     explicit List(const Data& dt);                 //#301//
     List(const List& lst);                         //#302//копирующий конструктор
     List& operator=(const List& lst);              //#303//копирующее присваивание
     ~List(){clear();}
 
     class Iterator;                                //#200//класс-член итератор
                                                    //перемещение по списку закольцовано
                                                    //признаком конца списка является 0
 
     Iterator begin();                              //#304//указывает на начало
     const Iterator begin() const;
     Iterator end();                                //#305//указывает на конец (фактически ссылается на 0)
     const Iterator end() const;
     Iterator insert(Iterator itr,const Data& dt);  //#306//вставка dt после элемента, на который установлен итератор itr
     Iterator erase(Iterator itr);                  //#307//удаление элемента, на который установлен итератор itr
 
     void push_back(const Data& dt);                //#308//вставка в конец списка
     void push_front(const Data& dt);               //#309//вставка в начало списка
     void pop_front();                              //#310//удаление начального элемента
     void pop_back();                               //#311//удаление конечного элемента
     void clear();                                  //#312//очистка списка
 
     typedef unsigned long size_type;
     size_type size() const {return _size;}         //размер списка
 
 private:
     class Node;                                    //#100//класс-член элемент списка
 
     size_type _size;
     Node* _head;
     Node* _tail;
 
     Node* create(const Data& dt,
                  Node* prev=0,
                  Node* next=0);                    //#313//динамическое создание элемента списка
 };
//#100//класс элемент списка------------------------
 template<class Data> class List<Data>::Node{
 public:
     Data _data;
     Node* _prev;
     Node* _next;
     Node(const Data& data, Node* prev=0, Node* next=0):_data(data),
                                                        _prev(prev),
                                                        _next(next){};
     //~Node(){std::cout<<'~'<<this<<std::endl;}
};
//#200//класс итератор------------------------------
template<class Data> class List<Data>::Iterator{
     Node* _curr;
     const List* _owner;                            //ссылается на экземпляр класса,
                                                    //которым был инициализирован
 public:
     friend class List;
     Iterator(Node* curr=0, const List* owner=0): _curr(curr),
                                                  _owner(owner){}
     Iterator& operator++();                        //#201//
     Iterator& operator--();                        //#202//
     bool operator==(const Iterator& itr) const;    //#203//
     bool operator!=(const Iterator& itr) const;    //#204//
 
     Data& operator*();                             //#205//разыменование
     const Data& operator*() const;
 };
//--------------------------------------------------
//#200//реализация класса итератор------------------
//#201//--------------------------------------------
template<class Data>
typename List<Data>::Iterator& List<Data>::Iterator::operator++(){
    if (!_owner) return *this;
    if (_curr) _curr=_curr->_next;
    else _curr=_owner->_head;
    return *this;
}
//#202//--------------------------------------------
template<class Data>
typename List<Data>::Iterator& List<Data>::Iterator::operator--(){
    if (!_owner) return *this;
    if (_curr) _curr=_curr->_prev;
    else _curr=_owner->_tail;
    return *this;
}
//#203//--------------------------------------------
template<class Data>
bool List<Data>::Iterator::operator==(const typename List<Data>::Iterator& itr) const{
    return _curr==itr._curr;
}
//#204//--------------------------------------------
template<class Data>
bool List<Data>::Iterator::operator!=(const typename List<Data>::Iterator& itr) const{
    return !(*this==itr);
}
//#205//--------------------------------------------
template<class Data>
Data& List<Data>::Iterator::operator*(){
    if (_curr) return _curr->_data;
    else throw std::out_of_range("Iterator::operator*()");
}
 
template<class Data>
const Data& List<Data>::Iterator::operator*()const{
    if (_curr) return _curr->_data;
    else throw std::out_of_range("Iterator::operator*()");
}
//--------------------------------------------------
//#300//реализация класса список--------------------
//#301//--------------------------------------------
template<class Data>
List<Data>::List(const Data &dt){
    List();
    _head=_tail=create(dt);
    _size++;
}
//#302//--------------------------------------------
template<class Data>
List<Data>::List(const List<Data> &lst){
    Iterator source=lst.begin();
    while(source!=lst.end()){
        push_back(*source);
        ++source;
    }
}
//#303//--------------------------------------------
template<class Data>
List<Data>& List<Data>::operator =(const List<Data> &lst){
    clear();
    Iterator source=lst.begin();
    while(source!=lst.end()){
        push_back(*source);
        ++source;
    }
    return *this;
}
//#304//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::begin(){
    return Iterator(_head,this);
}
 
template<class Data>
const typename List<Data>::Iterator List<Data>::begin() const{
    return Iterator(_head,this);
}
//#305//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::end(){
    return Iterator(0,this);
}
 
template<class Data>
const typename List<Data>::Iterator List<Data>::end() const{
    return Iterator(0,this);
}
//#306//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::insert(typename List<Data>::Iterator itr,
                                                 const Data &dt){
    if (itr==end()) return itr;
    Node* prev=itr._curr;
    ++itr;
    Node* succ=itr._curr;
    Node* curr=create(dt, prev, succ);
    if (prev) prev->_next=curr;
    else _head=curr;
    if (succ) succ->_prev=curr;
    else _tail=curr;
    _size++;
    return Iterator(curr);
}
//#307//--------------------------------------------
template<class Data>
typename List<Data>::Iterator List<Data>::erase(typename List<Data>::Iterator itr){
    if (itr==end()) return itr;
    Node* curr=itr._curr;
    ++itr;
    if (curr->_next) curr->_next->_prev=curr->_prev;
    else _tail=curr->_prev;
    if (curr->_prev) curr->_prev->_next=curr->_next;
    else _head=curr->_next;
    delete curr;
    _size--;
    return itr;
}
//#308//--------------------------------------------
template<class Data>
void List<Data>::push_back(const Data &dt){
    Node* curr=create(dt, _tail);
    if(_tail) _tail->_next=curr;
    else _head=curr;
    _tail=curr;
    _size++;
}
//#309//--------------------------------------------
template<class Data>
void List<Data>::push_front(const Data &dt){
    Node* curr=create(dt, 0, _head);
    if (_head) _head->_prev=curr;
    else _tail=curr;
    _head=curr;
    _size++;
}
//#310//--------------------------------------------
template<class Data>
void List<Data>::pop_front(){
    if (!_head) return;
    Node* curr(_head);
    _head=curr->_next;
    _head->_prev=0;
    delete curr;
    _size--;
}
//#311//--------------------------------------------
template<class Data>
void List<Data>::pop_back(){
    if (!_tail) return;
    Node* curr(_tail);
    _tail=curr->_prev;
    _tail->_next=0;
    delete curr;
    _size--;
}
//#312//--------------------------------------------
template<class Data>
void List<Data>::clear(){
    while (_head){
        Node* curr(_head);
        _head=curr->_next;
        delete curr;
        _size--;
    }
    _tail=_head;
}
//#313//--------------------------------------------
template<class Data>
typename List<Data>::Node* List<Data>::create(const Data &dt,
                                              typename List<Data>::Node *prev,
                                              typename List<Data>::Node *next){
    std::auto_ptr<Node> ptr(new Node(dt, prev, next));
    return ptr.release();
}

Сам код:

Кликните здесь для просмотра всего текста

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
#include <iostream>
#include "MyList.h"
//------------------
using std::cin;
using std::cout;
using std::endl;
//------------------
void change_const_list(const List<int>& list){
    List<int>::Iterator i=list.begin();
    while(i!=list.end()){
        *i=5;
        ++i;
    }
}
//------------------
int main(){
    List<int> lst;
    for (int i=0; i<10; ++i) lst.push_back(i);
 
    List<int>::Iterator iter;
    cout<<"original list: ";
    for (iter=lst.begin(); iter!=lst.end(); ++iter) cout<<*iter<<' ';
    cout<<endl;
 
    change_const_list(lst);//переписываем данные константного списка
 
    cout<<"changed list: ";
    for (iter=lst.begin(); iter!=lst.end(); ++iter) cout<<*iter<<' ';
    cout<<endl;
 
    system("pause");
    return 0;
}



0



Комп_Оратор)

Эксперт по математике/физике

8916 / 4677 / 626

Регистрация: 04.12.2011

Сообщений: 13,912

Записей в блоге: 16

08.03.2019, 04:25

19

Цитата
Сообщение от zayats80888
Посмотреть сообщение

Как я догадываюсь

Правильно догадываетесь.



1



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

08.03.2019, 04:25

Помогаю со студенческими работами здесь

Ошибка компилятора
Не работает cout и cin
Visual Studio 2008
Помогите пожалуста кто может:wall::wall::wall:

Ошибка Компилятора в C++
Здравствуйте дорогие программисты. Код очень странно работает. После того как он доходит до конца,…

ошибка компилятора
Не могу понять в чём проблема.Там ведь не нужна скобка и точка с запятой
П.5.18.Правил
Запрещено…

Ошибка компилятора
Пишет на последнюю строчку, что требуется while и синтаксическая ошибка }
#include &quot;stdafx.h&quot;…

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

Или воспользуйтесь поиском по форуму:

19

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Следующий код не компилируется. Там четыре типа ошибок компиляции. Список ошибок следующий:

Ошибка 4 ошибка C2665: «std::forward»: ни одна из двух перегрузок не может преобразовать все типы аргументов c:\program files (x86)\microsoft
visual studio 11.0\vc\include\future 1837
Ошибка 2 ошибка C2182: «_Val»: недопустимое использование типа «void» c:\program files (x86)\microsoft visual studio
11.0\vc\include\future 1027
Ошибка 3 ошибка C2182: «_Val»: недопустимое использование типа «void» c:\program files (x86)\microsoft visual studio
11.0\vc\include\future 1035
Ошибка 1 ошибка C2182: «_Get_value»: недопустимое использование типа «void» c:\program files (x86)\microsoft visual studio
11.0\vc\include\future 1020

#include<iostream>
#include<deque>
#include<mutex>
#include<future>
#include<thread>
#include<utility>

using namespace std;

std::deque<std::packaged_task<void()>> tasksList;
std::mutex mu;

void fun1(){cout<<"\n fun1 ";}
void fun2(){cout<<"\n fun2 ";}
void fun3(){cout<<"\n fun3 ";}
void fun4(){cout<<"\n fun4 ";}
void fun5(){cout<<"\n fun5 ";}
void fun6(){cout<<"\n fun6 ";}
void fun7(){cout<<"\n fun7 ";}
void fun8(){cout<<"\n fun8 ";}
void fun9(){cout<<"\n fun9 ";}
void fun10(){cout<<"\n fun10 ";}
void fun11(){cout<<"\n fun11 ";}
void fun12(){cout<<"\n fun12 ";}
void fun13(){cout<<"\n fun13 ";}
void fun14(){cout<<"\n fun14 ";}

bool flag = true;

bool isTrue(){return flag;}

void processTasks()
{
    //while(isTrue())
    {       
        if(tasksList.empty())
            return;
        std::packaged_task<void()> task;
        std::lock_guard<std::mutex> lock(mu);
        task = std::move(tasksList.front());
        tasksList.pop_front();
        task();
    }
}

template<typename fun>
std::future<void> addTasks(fun f)
{
    std::packaged_task<void()> task(f);
    std::future<void> res = task.get_future();
    std::lock_guard<std::mutex> lock(mu);
    tasksList.push_back(std::move(task));
    return res;
}

void addFunctions()
{
    addTasks(fun1);
    addTasks(fun2);
    addTasks(fun3);
    addTasks(fun4);
    addTasks(fun5);
    addTasks(fun6);
    addTasks(fun7);
    addTasks(fun8);
    addTasks(fun9);
    addTasks(fun10);
    addTasks(fun11);
    addTasks(fun12);
    addTasks(fun13);
    addTasks(fun14);    
}

int main()
{
    cout<<"\n End of Main \n";
    return 0;
}

Если мы прокомментируем строку tasksList.push_back(std::move(task)) функции AddTask(), тогда ошибка получит разрешение. Но это не решение. Я хочу переместить задачу из списка задач. Может кто-нибудь, пожалуйста, помогите мне запустить этот код?

2018-08-19 09:47

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

I get to help a lot of people learn C# programming every year. As I watch new developers grow and get used to working in C# and Visual Studio, it has become fairly clear to me that reading C# compiler errors and even their documentation is an acquired skill. I’ve made a request for Microsoft to improve the error message feedback in Visual Studio, but until that’s resolved developers still have a tough time working through early obstacles.

Because of this, I’m creating this unusual post to serve as beginner-friendly documentation to what I personally view as the most likely compiler errors a new developer is likely to encounter. Microsoft has wonderful documentation on compiler errors, and this is something that will help you out significantly as you grow, but early on a paragraph or two aimed at a beginner can be exactly what you need.

I also snuck in a few of the more interesting compiler errors I noticed about the maximum limits of the C# compiler, so even if you’re very familiar with C# at this point you’ll likely still learn a few things skimming this list.

Take a look at my list and my recommendations on these issues and let me know if you find this helpful or encounter something I missed.

CS0003 – Out of Memory

This occurs when a computer runs out of memory compiling your code. Close any unnecessary programs and reboot the machine if the problem persists.

CS0004 – Warning Treated as Error

Developers may configure projects to treat certain warnings as errors. These warnings may be specified in the build section of the project’s properties. Typically it is best to resolve the specific warning listed in the build errors since someone wanted that to be treated severely.

CS0015 – Type Name too Long

.NET requires the names of types and namespaces to be less than 1024 characters. If you find yourself getting this error, you may want to reconsider your team’s naming choices.

CS0017 – More than one entry point defined

This occurs when your program has more than one class defined with a static void main method. Remove one of them or manually set the project’s startup object in the project properties.

CS0019 – Operator ‘operator’ cannot be applied to operands of type ‘type’ and ‘type’

This occurs when you try to compare two different types in ways that cannot be compared. For example, checking to see if integer values are equal to Boolean values, subtracting a string from a number, etc. This error often occurs when developers forget what type of data is stored by a particular variable.

CS0020 – Division by Constant Zero

This occurs if you try to force a division by zero in your code. You cannot force a division by zero through a numeric literal or by using a constant for the denominator, but you can declare a variable holding 0 and use that as a denominator.

CS0021 – Cannot apply indexing to type

This occurs when you try to use an array or list-style indexer on a type that doesn’t support it. This often occurs when developers assume they’re working with an array, string, or list and are not.

CS0023 – Operator ‘operator’ cannot be applied to operand of type ‘type’

This occurs when you try to use a mathematical operator with a type that doesn’t support it. For example, trying to generate a negative value of a string. Double check that your variables are of the type you think they are and re-evaluate what you are trying to do.

CS0026 – Keyword this cannot be used in a static method

This error occurs when you are working inside of a static method and try to use the this keyword. Static methods are methods associated with the class itself and not with an instance of the class. As a result, static methods do not have access to any properties, methods, or fields on the class that are not static.

CS0029 – Cannot implicitly convert type ‘type’ to ‘type’

This occurs when you have a variable of one type and are trying to store it into a variable of another type. Some types allow you to automatically convert from one type to another (an implicit conversion), but the types you are using do not support that. You may need to use an explicit cast using (type) syntax.

CS0030 – Cannot convert type ‘type’ to ‘type’

This occurs when there is no implicit or explicit conversion between two different types. If you’re sure you need to do what you’re doing, you could create a method to convert from one type to the other.

CS0031 – Constant value ‘value’ cannot be converted to a ‘type’.

This occurs when you try to store a value into a variable type that cannot store that particular value. For example, if you try to store 5 billion into an integer (which can store values up to around 2.1 billion) you will get this compiler error. You can resolve this error by storing the value into a type that can hold larger values, such as a long.

CS0050 – Inconsistent accessibility: return type ‘type’ is less accessible than method ‘method’

This occurs when a method returns a type that has a visibility or access modifier that is more restrictive than the method and class the method is currently in. For example this error will occur if a public method in a public class returns a type that is defined as internal.

This error usually occurs when developers forget to mark a class as public. Remember that classes have a default access modifier of internal when no access modifier is specified. Typically the fix for this is to explicitly declare that class as public.

CS0051 – Inconsistent accessibility: parameter type ‘type’ is less accessible than method ‘method’

This occurs when a method takes in a parameter that is of a type that has a visibility or access modifier that is more restrictive than the method and class the method is currently in. For example this error will occur if a public method in a public class requires a parameter of a type that is defined as internal.

This error usually occurs when developers forget to mark a class as public. Remember that classes have a default access modifier of internal when no access modifier is specified. Typically the fix for this is to explicitly declare that class as public.

CS0052 – Inconsistent accessibility: field type ‘type’ is less accessible than field ‘field’

This occurs when a class has a public field that is of a type that has a visibility or access modifier that is more restrictive than the class the method is currently in. For example this error will occur if a class has a public field of a type that is defined as internal.

This error usually occurs when developers forget to mark a class as public. Remember that classes have a default access modifier of internal when no access modifier is specified. Typically the fix for this is to explicitly declare that class as public.

CS0053 – Inconsistent accessibility: property type ‘type’ is less accessible than property ‘property’

This occurs when a class has a property of a type that has a visibility or access modifier that is more restrictive than the property’s visibility. For example this error will occur if a public property is of a type that is defined as internal.

This error usually occurs when developers forget to mark a class as public. Remember that classes have a default access modifier of internal when no access modifier is specified. Typically the fix for this is to explicitly declare that class as public.

CS0060 – Inconsistent accessibility: base class ‘class1’ is less accessible than class ‘class2’

This occurs when a class inherits from another class but the subclass’s access modifier is less restrictive than the base class’s access modifier. For example this error will occur if a public class inherits from an internal class.

This error usually occurs when developers forget to mark a class as public. Remember that classes have a default access modifier of internal when no access modifier is specified. Typically the fix for this is to explicitly declare that class as public.

CS0061 – Inconsistent accessibility: base interface ‘interface 1’ is less accessible than interface ‘interface 2’

This occurs when an interface inherits from another interface but the child interface’s access modifier is less restrictive than the base interface’s access modifier. For example this error will occur if a public interface inherits from an internal interface.

This error usually occurs when developers forget to mark an interface as public. Remember that interfaces have a default access modifier of internal when no access modifier is specified, although every member of an interface is public. Typically the fix for this is to explicitly declare that interface as public.

CS0100 – The parameter name ‘parameter name’ is a duplicate

This occurs when a developer declares a method but uses the same parameter name twice in the method’s parameter list. The fix for this is generally to remove an unneeded parameter or to rename parameters so that all parameters have a different name.

CS0101 – The namespace ‘namespace’ already contains a definition for ‘type’

This occurs when a class is defined twice in the same namespace. This can occur when a class is renamed but the old file still exists, when a developer forgot to mark a class as part of a different namespace, or when a developer intended to use the partial keyword but forgot to specify it. The fix for this will vary based on which files you want and what namespaces they should live in.

CS0102 – The type ‘type name’ already contains a definition for ‘identifier’

This occurs when you declare a member such as a field twice in the same class. Often this is a symptom of using an existing variable name instead of choosing a new name.

CS0103 – The name ‘identifier’ does not exist in the current context

This error often occurs when trying to use a variable defined in another scope. This commonly occurs when you try to define a variable inside of a try block and refer to it in a catch block, when there was no guarantee that the runtime was able to create that variable and therefore the variable is not available.

The fix for this is typically to declare the variable before the try / catch block and update its value from the try block. In this way the catch block will get either the initial value of the variable or its updated value and will be able to reference it.

CS0111 – Type ‘class’ already defines a member called ‘member’ with the same parameter types

This occurs when a developer creates a duplicate method or property with an identical signature consisting of a return type and parameter types. The compiler detects that there will not be a way for code outside of the class to distinguish between one member and the other and so this error is raised. Typically when this occurs you need to either rename one of the two members, change the parameters of one of the methods, or merge the two methods together into one method.

CS0117 – ‘type’ does not contain a definition for ‘identifier’

This occurs when you are trying to call a method or use a property on an instance of an object, but there is no method or property with that name. This can be an issue with capitalization, spelling, or forgetting the name of the member you’re referring to. Code completion can help you find the correct name to use.

CS0120 – An object reference is required for the non-static field, method, or property ‘member’

This often occurs in static methods when you attempt to work with non-static members of the same class. Remember that static methods are associated with the class itself and not with a specific instance of that class. As a result, static methods cannot access properties, fields, and methods that are not marked as static.

The fix for this is often to remove the static keyword from the method that needs to access instance variables. This is counter-intuitive since the compiler pushes you towards adding static in other places, but if you follow that path to its logical conclusion all of your data becomes static eventually, so you’re better off removing the static keyword when confronted by this.

CS0122 – ‘member’ is inaccessible due to its protection level

This occurs when you are trying to call a method or use a property on an instance of an object, but that member is defined as private or protected and you are outside of the class or something that inherits from it. You may not be intended to work with the method or property you are using and you should probably look for public members that might meet your needs without compromising the class’s encapsulation.

CS0127 – Since ‘function’ returns void, a return keyword must not be followed by an object expression

This is a rarer error that occurs when you are in a method defined as void but are trying to return a specific object. Remember that void methods do not return any value so a return statement should just be listed as return;. If you find that you do need to return a value, you should change the return type of the method from void to some specific type.

CS0128 – A local variable named ‘variable’ is already defined in this scope

This occurs when you re-declare a variable that already exists. The solution for this is to either use a different variable name or to remove the type name from your statement and change it from a variable declaration to an assignment statement and re-use the existing variable.

This error often comes from copying and pasting code that declares a new variable.

CS0133 – The expression being assigned to ‘variable’ must be constant

This occurs when you are declaring a const and declaring it to another variable. Constants are evaluated at the time your code is compiled and the compiler will not know the value of your variables. As a result, constants must be set to a literal number or string value.

CS0134 – ‘variable’ is of type ‘type’. A const field of a reference type other than string can only be initialized with null.

This occurs when you are trying to declare a const of a type other than a numeric or string value. Typically, if you have a const that needs to store a reference type you should instead use readonly which is less optimized than a const but works with reference types and ensures that the value will never change.

CS0136 – A local variable named ‘var’ cannot be declared in this scope because it would give a different meaning to ‘var’, which is already used in a ‘parent or current/child’ scope

This occurs when you declare a new variable with the same name as another variable in a visible scope. The solution for this is to either use a different variable name or to remove the type name from your statement and change it from a variable declaration to an assignment statement and re-use the existing variable.

CS0145 – A const field requires a value to be provided

This occurs when you declare a const but do not provide a value. You should set a const equal to some string or numeric variable when declaring it.

CS0150 – A constant value is expected

This occurs when the compiler requires a constant value such as a numeric or string literal but a variable is defined. This can occur when you use a variable in a switch statement or when you are using an array initializer for an array with a variable size.

Switch statements cannot use cases for specific variables, though switch expressions are more flexible.

When working with arrays of varying size, you may want to avoid the use of array initializers and instead manually set the elements of the array after creation.

CS0152 – The label ‘label’ already occurs in this switch statement

This occurs when you duplicate a case statement inside of a switch statement. Typically this occurs when you didn’t notice the case already existed and you can delete your repeated case statement.

CS0160 – A previous catch clause already catches all exceptions of this or of a super type (‘type’)

The ordering of catch statements in a try / catch matters since the runtime will try to match the first catch that applies to the exception it encountered. Because of this, the compiler generates this error if it sees a more specific exception type after a less specific exception type since this results in a case where the more specific catch statement could never be reached.

Move your more specific catch statement above the less specific one to fix this error.

CS0161 – Not all code paths return a value

This occurs because the C# compiler believes that it is possible to get to the end of your method without encountering a return statement. Keep in mind that the C# compiler does very little inferences based on your if statements and even if it may not actually be possible to reach the end of the method without returning, the compiler still thinks it is.

The fix for this is almost always to add a final return statement.

CS0165 – Use of unassigned local variable

This occurs when the compiler sees a variable that is defined but not set to an initial value and determines that the value of that variable needs to be read from later on in the method before the variable is guaranteed to have its value set.

The fix for this is generally to set the variable to be equal to an initial value.

CS0176 – Static member ‘member’ cannot be accessed with an instance reference; qualify it with a type name instead

This occurs when you have a static property or field on a class but are trying to refer to it on a specific instance of that class.

Use the class name instead of the instance variable to access the static member.

CS0201 – Only assignment, call, increment, decrement, and new object expressions can be used as a statement

This typically occurs when you are performing some sort of mathematical operation but not storing the result into a variable. The compiler understands the operation but sees it has no value, so it raises the error.

The fix for this is to store the result of the mathematical operation into a variable or to remove the unnecessary line.

CS0204 – Only 65534 locals are allowed

Apparently you have a method that has over 65 thousand local variables inside of it. The compiler doesn’t like this very much and, frankly, I’m a little concerned why you’d need that many.

Reconsider your life choices.

CS0230 – Type and identifier are both required in a foreach statement

This occurs when you are writing a foreach statement without specifying all parts of the statement.

foreach statements require a variable type, a variable name, the word in, and some variable that can be enumerated over. For example: foreach (string person in people)

CS0234 – The type or namespace name ‘name’ does not exist in the namespace ‘namespace’ (are you missing an assembly reference?)

This occurs when you are trying to refer to a type via its fully-qualified name, including the namespace, but no known type exists with that namespace and type name. This can be a spelling error, a mistake as to which namespace the type lives in, or a correct namespace and type, but your project does not yet have a reference to the project the type is defined in.

If your spelling and namespaces are correct you may need to add a project reference to your project or install a package via nuget.

CS0236 – A field initializer cannot reference the non-static field, method, or property ‘name’.

This occurs when you try to define a field by referencing another field. This error exists to prevent unpredictable behavior based on which field initializers run first.

The fix for this is to set the value of the field in the constructor instead of in a field initializer.

CS0246 – The type or namespace name ‘type/namespace’ could not be found (are you missing a using directive or an assembly reference?)

This occurs when you are trying to refer to a type no known type exists with that type name in the using statements currently in your file.

This is usually a spelling error or a missing using statement at the top of your file.

If your spelling and using statements are correct you may need to add a project reference to your project or install a package via nuget.

CS0266 – Cannot implicitly convert type ‘type1’ to ‘type2’. An explicit conversion exists (are you missing a cast?)

This occurs when you are trying to store a variable of one type into a variable of another type without casting. For example, if you are trying to set a double value into an int variable you will see this error.

The statement “an explicit conversion exists (are you missing a cast)” is telling you that these types are compatible, but the compiler wants to make sure you intend to convert from one to another so it requires you to cast your variable from one type to another.

You cast variables in C# by using parentheses around a type name like this: int num = (int)myDouble;

CS0500 – ‘class member’ cannot declare a body because it is marked abstract

This occurs when you declare an abstract member inside of an abstract class, but you tried to give it a method body (using {}). Abstract members do not have method bodies.

Remove the  {}’s from your abstract method. Alternatively, if you want to provide a default implementation and allow inheriting classes to optionally override yours, use virtual instead of abstract.

CS0501 – ‘member function’ must declare a body because it is not marked abstract, extern, or partial

This occurs when you try to declare a method but forget to give it a method body with {}’s.

This can also occur when you mean to define an abstract method but forgot to use the abstract keyword.

CS0506 – ‘function1’ : cannot override inherited member ‘function2’ because it is not marked “virtual”, “abstract”, or “override”

In C# you have to mark a method as virtual or abstract to be able to override it.

The fix for this is usually to add the virtual keyword to the method in the base class.

CS0507 – ‘function1’ : cannot change access modifiers when overriding ‘access’ inherited member ‘function2’

When overriding a method you must keep the same access modifier as the base method. If the access modifier needs to change, change it in all classes that have the method.

CS0508 – ‘Type 1’: return type must be ‘Type 2’ to match overridden member ‘Member Name’

When overriding a method you cannot change the return type of the method. If you think you need to return something radically different, you may need to introduce a new method instead of overriding an existing one. Alternatively, creative uses of interfaces or inheritance can allow you to return a more specific version of something from a method through polymorphism.

CS0513 – ‘function’ is abstract but it is contained in nonabstract class ‘class’

When you need a method to be abstract, the entire class needs to be abstract as well.

CS0525 – Interfaces cannot contain fields

This one is self-explanatory. An interface is a contract that defines what members need to be present. Fields in classes should be private and are implementation details that do not belong in an interface.

CS0526 – Interfaces cannot contain constructors

This one is self-explanatory. An interface is a contract that defines what members need to be present on an already-constructed class. Interfaces do not care about how an instance is created and cannot denote constructors required for a given class.

CS0531 – ‘member’ : interface members cannot have a definition

This occurs when you try to give an interface member a method body. Interfaces denote capabilities that must be in place, not how those capabilities should work.

If you think you really need a default implementation of a method, you might want to use an abstract class instead of an interface.

CS0534 – ‘function1’ does not implement inherited abstract member ‘function2’

This occurs when you inherit from an abstract class that has abstract members but do not override those members. Because of this, the compiler has no implementation for those abstract members and does not know how to handle them if they are called.

Override the inherited member or mark the inheriting class as abstract as well.

CS0535 – ‘class’ does not implement interface member ‘member’

This occurs when you implement an interface but have not provided members that match those defined in the interface. Members must match the exact type signatures of those defined in the interface and should have names that match those in the interface as well.

CS0645 – Identifier too long

This occurs when you try to name a variable or other identifier something longer than 512 letters long.

What exactly are you trying to do over there that has you naming variables this long?

CS0844 – Cannot use local variable ‘name’ before it is declared.

This occurs when you try to use a variable in a method above when that variable is declared. C# does not have hoisting like some other languages do and variables are only available after they are declared.

Reorder your statements to match your needs.

CS1001 – Identifier expected

This usually occurs when you forget the name of a variable, class, or parameter but have defined other aspects of that line of code. Check some reference materials for what you are trying to do because you’re missing something important.

CS1002 – Semicolon expected

C# requires you to end most statements with a semicolon, including this one. Add a semicolon to the end of the line and all should be well.

CS1026 – ) expected

You have too many opening parentheses and not enough closing parentheses. Check to make sure that all open-parentheses have a matching closing parentheses.

Clicking on a parentheses in Visual Studio will highlight the matching parentheses making it easier to spot the one you’re missing.

CS1033 – Source file has exceeded the limit of 16,707,565 lines representable in the PDB; debug information will be incorrect

What on earth are you even doing over there? Why would you have a source file that requires more than 16 million lines?

Don’t do that. Just no. It’s time to hire a consultant.

CS1034 – Compiler limit exceeded: Line cannot exceed ‘number’ characters

Some people like tabs. Some people like spaces. You, apparently solve this debate by removing line breaks entirely.

You should never need to have a line of code longer than 16 million characters.

CS1035 – End-of-file found, ‘*/’ expected

Your code has a block comment start (/*) but no matching end comment. Add an end comment (*/) and the compiler will be happier.

CS1039 – Unterminated string literal

It looks like you started a string somewhere but forgot to put the other quotation mark. Add it in where it needs to be.

CS1501 – No overload for method ‘method’ takes ‘number’ arguments

This occurs when you are trying to call a method with an incorrect number of arguments or parameters to that method. Check the code or documentation for the method you’re trying to call and ensure you have the correct number of arguments specified.

CS1513 – } expected (missing closing scope)

You have too many opening curly braces and not enough closing curly braces. Check to make sure that all open curly braces have a matching closing curly brace.

Clicking on a { in Visual Studio will highlight the matching } making it easier to spot the one you’re missing.

CS1514 – { expected

Your code requires a { but you didn’t provide one. This often happens after declaring a namespace or class. Check your syntax and add curly braces where they need to go.

CS1525 – Invalid expression term ‘character’

This error seems ambiguous, but most of the time when I see this error it comes from someone trying to use == to assign a value to a variable instead of using the = operator. If this is not your error, you may need to consult some documentation or reference material for valid syntax for what you’re trying to do.

CS1552 – Array type specifier, [], must appear before parameter name

This error occurs when you put [] syntax around the variable name and not around the type name when declaring an array.

Write your arrays as int[] myArray; instead of int myArray[];.

CS1604 – Cannot assign to ‘variable’ because it is read-only

This occurs when you’ve declared a readonly or const variable and are trying to set its value. You can’t do that. If you need to change its value, it can’t be readonly or const.

CS7036 – No argument given that corresponds to the required formal parameter (incorrect method call)

This error occurs when trying to call a base constructor but not specifying a parameter that is required by that constructor.

Double check your base() call and make sure the number and types of parameters lines up with a specific constructor present on your base class.

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ошибка компилятора c2381
  • Ошибка коммуникации что это
  • Ошибка компилятора c2664
  • Ошибка ккт 4459 атол при пробитии чека
  • Ошибка компилятора c2361

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: