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

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2665

Compiler Error C2665

11/04/2016

C2665

C2665

a7f99b61-2eae-4f2b-ba75-ea68fd1e8312

Compiler Error C2665

‘function’ : none of the number1 overloads can convert parameter number2 from type ‘type’

A parameter of the overloaded function cannot be converted to the required type. Possible resolutions:

  • Supply a conversion operator.

  • Use explicit conversion.

Example

The following sample generates C2665.

// C2665.cpp
void func(short, char*){}
void func(char*, char*){}

int main() {
   func(0, 1);   // C2665
   func((short)0, (char*)1);   // OK
}

zayats80888

5884 / 3288 / 1351

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

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

1

06.03.2019, 18:42. Показов 2885. Ответов 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



5884 / 3288 / 1351

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

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

06.03.2019, 19:54

 [ТС]

3

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

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

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

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

1>c:usersartherdocumentsvisual studio 2008projectstest 2MyList.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:usersartherdocumentsvisual studio 2008projectstest 2MyList.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:usersartherdocumentsvisual studio 2008projectstest 2MyList.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:usersartherdocumentsvisual studio 2008projectstest 2MyList.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:usersartherdocumentsvisual studio 2008projectstest 2MyList.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:usersartherdocumentsvisual studio 2008projectstest 2MyList.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:usersartherdocumentsvisual studio 2008projectstest 2MyList.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

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

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

8852 / 4593 / 620

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

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

Записей в блоге: 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

5884 / 3288 / 1351

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

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

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



5884 / 3288 / 1351

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

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

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

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

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

8852 / 4593 / 620

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

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

Записей в блоге: 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

5884 / 3288 / 1351

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

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

06.03.2019, 22:52

 [ТС]

12

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

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

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

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

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

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

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

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

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

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

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

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

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

C++
1
 List<int> lst;

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



0



IGPIGP

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

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

8852 / 4593 / 620

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

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

Записей в блоге: 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



5884 / 3288 / 1351

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

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

06.03.2019, 23:15

 [ТС]

14

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



0



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

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

8852 / 4593 / 620

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

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

Записей в блоге: 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

5884 / 3288 / 1351

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

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

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



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

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

8852 / 4593 / 620

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

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

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

08.03.2019, 01:41

17

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

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

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

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



1



zayats80888

5884 / 3288 / 1351

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

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

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



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

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

8852 / 4593 / 620

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

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

Записей в блоге: 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

in file.hpp I got

void func(std::vector<double>& vec, const std::pair<const A, const B>& map,
          const C& swap, const V* v, const D& date1, const D& date2, const int dim);

in file2.cpp

void func2(std::vector<double>& vec, const A& p1, const B& p2,
          const C& swap, const V* v, const D& date1, const D& date2, const int dim) {
    func(vec, make_pair(p1, p2), swap, v , date1, date2, dim);
}

The error lies in the line func(vec, std::make_pair<p1, p2>, swap, v, date1, date2, dim)

it says: none of the two overloads could convert all the arguments types (I have overloaded the func function)

  • Remove From My Forums
  • Question

  • #include «peg.hpp»

    enum StringIds
    {
    SID_HELLO = FIRST_USER_STRING,
    SID_FIRST_WIN
    };

    PEGCHAR HelloString[] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,’W’,’o’,’r’,’l’,’d’, ‘o’};

    PEGCHAR FirstString[] = {‘M’,’y’,’ ‘,’F’,’i’,’r’,’s’,’t’,’ ‘,’W’,’i’,’n’,’d’,’o’,’w’, ‘o’};

    void PegAppInitialize(PegPresentationManager *pPresent)
    {
    PegResourceManager::AddResource(SID_HELLO, HelloString);

    PegResourceManager::AddResource(SID_FIRST_WIN, FirstString);

    PegMessageWindow *pWin = new PegMessageWindow(SID_HELLO,

               

                 SID_FIRST_WIN, FF_RAISED|MW_OK); // note 1
    pPresent->Center(pWin); // note 2
    pPresent->Add(pWin); // note 3
    }

    Getting the errors as

    Compiling…
    startup.cpp
    C:swellsoftwarepegplusstartup.cpp(15) : error C2665: ‘AddResource’ : none of the 4 overloads can convert parameter 1 from type ‘enum StringIds’
    C:swellsoftwarepegplusstartup.cpp(17) : error C2665: ‘AddResource’ : none of the 4 overloads can convert parameter 1 from type ‘enum StringIds’
    Error executing cl.exe.

    startup.obj — 2 error(s), 0 warning(s)

    I am using Microsoft visaul C++ 6.0 in XP platform pls help me out

Answers

  • Enums are integral types, but there is no implicit conversion offered by the compiler. You can use explicit conversion through casting to eliminate the error.

    PegResourceManager::AddResource((UINT)SID_HELLO, HelloString);

    Are you sure those strings are correct? (That is not a 0 terminator…its the letter o.)

    PEGCHAR HelloString[] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,’W’,’o’,’r’,’l’,’d’, 0};

    PEGCHAR FirstString[] = {‘M’,’y’,’ ‘,’F’,’i’,’r’,’s’,’t’,’ ‘,’W’,’i’,’n’,’d’,’o’,’w’, 0};

    This is an easier way…

    PEGCHAR HelloString[] = «Hello, World»;

    PEGCHAR FirstString[] = «My First Window;

    • Edited by

      Thursday, October 22, 2009 3:51 PM
      add comment about strings

    • Marked as answer by
      Wesley Yao
      Monday, October 26, 2009 6:12 AM

#c #overloading

Вопрос:

во file.hpp мне есть

 void func(std::vector<double>amp; vec, const std::pair<const A, const B>amp; map,
          const Camp; swap, const V* v, const Damp; date1, const Damp; date2, const int dim);
 

в file2.cpp

 void func2(std::vector<double>amp; vec, const Aamp; p1, const Bamp; p2,
          const Camp; swap, const V* v, const Damp; date1, const Damp; date2, const int dim) {
    func(vec, make_pair(p1, p2), swap, v , date1, date2, dim);
}
 

Ошибка кроется в строке func(vec, std::make_pair<p1, p2>, swap, v, date1, date2, dim)

в нем говорится: ни одна из двух перегрузок не смогла преобразовать все типы аргументов (я перегрузил func функцию).

Комментарии:

1. Похоже , ты зарабатываешь std::pair<const Aamp;, const Bamp;> , нет?

2. Ваш блок кода и следующая строка несовместимы: у вас было std::make_pair<p1,p2> или make_pair(p1, p2) ? Оба варианта неверны, но первый дает сообщение об ошибке. Должно быть гибридом двух: std::make_pair(p1, p2) .

3. в моем коде это std::make_pair(p1, p2) извините

4. Тогда… не воспроизводимо. Я дал несколько фиктивных определений для ваших A, B, C, D, V типов, и код компилируется.

5. Но, как говорит @AlexeyLarionov, возможно A , проблема в ссылках на B и в этом — трудно сказать, не зная, как определяются эти типы.

  • Remove From My Forums
  • Question

  • I’ve run into a bug in the compiler that’s preventing me from building.  I have a class with two constructors which are clearly totally from each other:

    ColumnDrawInfo(const CString& inLabel, COLORREF inText, HFONT inFont, UINT inTextAlignment = DT_LEFT);
    ColumnDrawInfo(UINT inLabel, COLORREF inText, HFONT inFont, UINT inTextAlignment = DT_LEFT);

    But when I try to create an instance with that second constructor the compiler fails:

    error C2665: ‘ColumnTreeContainer::ColumnDefinition::ColumnDefinition’ : none of the 2 overloads can convert parameter 1 from type ‘UINT’
    could be ‘ColumnTreeContainer::ColumnDefinition::ColumnDefinition(const ATL::CString &,size_t,UINT)’
            while trying to match the argument list ‘(UINT, int, int)’

    Bullshit.

    The compiler is especially stubborn with this.  I’ll get the same error even when I comment out that first version with the string.  I only have 1 version of this file on my system so it can’t be blamed on the compiler picking up another version.

    Are there any pragmas that I can use to get around this compiler error?  Something like:

    #pragma SUPPORT_OVERLOADING_PROPERLY

    I have VS.NET 2003

    Thanks

Answers

  • You are using the ColumnTreeContainer::ColumnDefinition constructor; however, your orignal post shows constructors for a different class. Check your types.

  • As has been stated, you are posting the constructors to a different class.  Those constructors do not exist for the type you are trying to construct — ColumnTreeContainer::ColumnDefinition — instead, try using one of ColumnTreeContainer::ColumnDefinition’s constructors.  The error gave you the definition of one: ‘ColumnTreeContainer::ColumnDefinition::ColumnDefinition(const ATL::CString &,size_t,UINT).  You cannot use the constructor from class A to construct class B.  This is not a compiler bug, that’s how C++ works. 

    No need to get ornery — we’re here to help.

    -Ben

Начинающий изучающий VC, напишите следующий код для запуска, и он выдает ошибку (ошибка C2665: «AfxMessageBox»: ни одна из двух перегрузок не может преобразовать все типы параметров).

      Код: 1 пусто CMouseMoveView :: OnAppExit ()

          2 {

                     3 // TODO: добавьте сюда код обработчика команд

                     4 if (AfxMessageBox («Вы действительно хотите выйти из текущей программы?», MB_YESNO) == IDYES)

          5 AfxGetMainWnd()->SendMessage(WM_CLOSE);

          6 }

Метод 1. Измените четвертую строку на: if (AfxMessageBox (_T («Вы действительно хотите выйти из текущей программы?»), MB_YESNO) == IDYES)

Или измените четвертую строку на: if (AfxMessageBox (L «Вы действительно хотите выйти из текущей программы?», MB_YESNO) == IDYES)

Метод 2: выберите меню «Проект» -> Свойства проекта -> Свойства конфигурации -> Общие -> Набор символов и измените его на «Не задано».

Это связано с тем, что vs2005 использует кодировку символов юникода, установленную по умолчанию, а юникод занимает 2 байта, а обычный символ занимает только 1 байт, поэтому его нельзя преобразовать, поэтому вам нужно добавить _T или L для преобразования.

Понравилась статья? Поделить с друзьями:
  • Ошибка компилятора c2614
  • Ошибка компиляции для платы arduino genuino uno
  • Ошибка компилятора c2572
  • Ошибка компиляции для платы ai thinker esp32 cam
  • Ошибка компиляции встроенного языка