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 куда не нужно, ничего не вышло(тема для меня сложная). Кликните здесь для просмотра всего текста
0 |
Параллельный Кот 1905 / 827 / 350 Регистрация: 25.03.2016 Сообщений: 2,045 |
|
06.03.2019, 19:40 |
2 |
Ошибка компилятора 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, ^~~~~~~~~~ Оставьте значения по умолчанию только в объявлении.
можно ли реализацию методов моих классов переместить в отдельный *.cpp? Вряд ли. У вас это не класс, а шаблон класса. Какую реализацию должен сделать компилятор в объектном файле без конкретизации типов? Есть способы заставить сделать реализацию для конечного набора типов, но тогда ваш список будет работать только с этим набором.
1 |
5884 / 3288 / 1351 Регистрация: 07.02.2019 Сообщений: 8,310 |
|
06.03.2019, 19:54 [ТС] |
3 |
Оставьте значения по умолчанию только в объявлении. вы правы, только у меня 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
0 |
valen10 Параллельный Кот 1905 / 827 / 350 Регистрация: 25.03.2016 Сообщений: 2,045 |
||||
06.03.2019, 20:15 |
4 |
|||
zayats80888, покажите пример использования, на котором возникает эта ошибка, чтобы его можно было скомпилировать.
Еще обратите внимание на то, что auto_ptr считается deprecated.
1 |
IGPIGP Комп_Оратор) 8852 / 4593 / 620 Регистрация: 04.12.2011 Сообщений: 13,718 Записей в блоге: 16 |
||||
06.03.2019, 20:27 |
5 |
|||
zayats80888,
до этого я просто выбрасывал исключения в операторах ++ и — на границах списка Это скорее всего неверно. То есть, сделать то можно всё, но имеет смысл соблюдать семантику контейнеров уже существующих сегодня. Я о том, что итераторы не знают о том куда они указывают, как и указатели. Именно в этом и ценность. Начало и конец — собственность конкретного объекта контейнера и проверка — дело клиентского кода.
как видите доступ к
1 |
zayats80888 5884 / 3288 / 1351 Регистрация: 07.02.2019 Сообщений: 8,310 |
||||
06.03.2019, 20:28 [ТС] |
6 |
|||
покажите пример использования, да аналогичный вашему, просто тестирую Кликните здесь для просмотра всего текста
А мусор может потому, что Iterator не имеет доступа к приватным членам класса List(не видит _head, _tail)?
0 |
Параллельный Кот 1905 / 827 / 350 Регистрация: 25.03.2016 Сообщений: 2,045 |
|
06.03.2019, 20:39 |
7 |
А мусор может потому, что Iterator не имеет доступа к приватным членам класса List(не видит _head, _tail)? Нет, начало выводится нормально.
. Результат для кода, приведенного выше:
Или это какая-то отладочная печать? Все, заметил
1 |
5884 / 3288 / 1351 Регистрация: 07.02.2019 Сообщений: 8,310 |
|
06.03.2019, 20:49 [ТС] |
8 |
компиляция без ошибок А чем вы компилируете?
0 |
valen10 Параллельный Кот 1905 / 827 / 350 Регистрация: 25.03.2016 Сообщений: 2,045 |
||||
06.03.2019, 21:52 |
9 |
|||
Сообщение было отмечено 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); ^~~~~~~~~~~~~~~~ Вызов происходит отсюда:
Нельзя просто так взять и сделать константный указатель неконстантным. В STL, кажется, для такого случая используется отдельный итератор const_iterator. Как исправить, увы, не подскажу, ибо в такие дебри лазить еще не приходилось. Надеюсь, эта отсылка к строке с ошибкой наведет вас на верные мысли.
1 |
IGPIGP Комп_Оратор) 8852 / 4593 / 620 Регистрация: 04.12.2011 Сообщений: 13,718 Записей в блоге: 16 |
||||
06.03.2019, 22:15 |
10 |
|||
zayats80888, у вас операции для итератора — набор странностей. Присваивание итератора не должно работать ни с чем кроме адреса. Не нужно бежать по всему контейнеру от начала. Вот этот код работает
печатая в конце какие-то адреса. Нельзя понять где у вас те сообщения компилятора потому что:
покажите пример использования, на котором возникает эта ошибка, чтобы его можно было скомпилировать.
1 |
valen10 Параллельный Кот 1905 / 827 / 350 Регистрация: 25.03.2016 Сообщений: 2,045 |
||||
06.03.2019, 22:28 |
11 |
|||
IGPIGP, замените main() на этот:
Получите ошибку из поста #9. Начинается всё с оператора копирования и приводит в код создания константного итератора, где что-то не так.
1 |
zayats80888 5884 / 3288 / 1351 Регистрация: 07.02.2019 Сообщений: 8,310 |
||||
06.03.2019, 22:52 [ТС] |
12 |
|||
у вас операции для итератора — набор странностей. Ну я тока учусь, куда же без них
Присваивание итератора не должно работать ни с чем кроме адреса. Это вы наверное про копирующее присваивание класса List. Я там через итераторы реализовать решил. И ошибка похоже именно там.
Нельзя просто так взять и сделать константный указатель неконстантным. Да, похоже в этом и ошибка. В любом случае, спасибо, за потраченное на помощь время. Полезу изучать матчасть. Добавлено через 5 секунд
замените main() на этот: забыл сказать, что у меня конструктор по умолчанию не реализован для итератора, так что
не прокатывает, но это ошибка другого рода.
0 |
IGPIGP Комп_Оратор) 8852 / 4593 / 620 Регистрация: 04.12.2011 Сообщений: 13,718 Записей в блоге: 16 |
||||
06.03.2019, 23:11 |
13 |
|||
Сообщение было отмечено zayats80888 как решение Решение
Получите ошибку из поста #9. Начинается всё с оператора копирования и приводит в код создания константного итератора, где что-то не так. Спасибо, — посмотрю. cv в контейнерах это вообще морока, так как нельзя инстанцироваться на <const T> Добавлено через 17 минут
Начинается всё с оператора копирования и приводит в код создания константного итератора, где что-то не так. Метод объявлен константным потому-что, я думаю.
Я просто убрал константность даже в конструкторе копий. Нельзя предоставить указатель на внутренности (неконстантный) и ждать что компилятор позволит доступ внутрь константного объекта (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 |
Если в итераторе убрать ссылку на список Её там быть не должно. Итератор не знает о контейнере (конкретном объекте).
Только я не знаю, как реализовать Iterator—, если он установлен на end() Можно и создать. Но вообще, возможность декрементировать end() это поиск неприятностей. Где это может быть необходимо? zayats80888, даже при реализации reverse_iterator вам нужно отыскать последний фактический итератор (тот что перед end()), и это делается пробежкой до end() при наличии ещё одной переменной навродь iter_prev — предыдущий по отношению к переменной итерации Добавлено через 20 минут
Её там быть не должно. Итератор не знает о контейнере (конкретном объекте). тут я сморозил чушь. Давно не писал чего-то похожего.
1 |
zayats80888 5884 / 3288 / 1351 Регистрация: 07.02.2019 Сообщений: 8,310 |
||||
07.03.2019, 18:53 [ТС] |
16 |
|||
Почесав репу, удалось решить исходную проблему, просто объявив поле _owner и параметр конструктора итератора как указатели на константный объект: Кликните здесь для просмотра всего текста
И все же, следуя вашим советам, я пересмотрю функционал итератора. Всем спасибо за помощь.
0 |
Комп_Оратор) 8852 / 4593 / 620 Регистрация: 04.12.2011 Сообщений: 13,718 Записей в блоге: 16 |
|
08.03.2019, 01:41 |
17 |
просто объявив поле _owner Беда в том, что вы получите итератор через который сможете выполнять только константные операции. Например, вывод в поток. Но вы же наверняка планируете и писать через итератор? Добавлено через 15 минут
1 |
zayats80888 5884 / 3288 / 1351 Регистрация: 07.02.2019 Сообщений: 8,310 |
||||||||
08.03.2019, 03:29 [ТС] |
18 |
|||||||
Беда в том, что вы получите итератор через который сможете выполнять только константные операции. Почему же? Поле _owner не используется для доступа к самим данным, хранящимся в контейнере. Как писал в топике, я ввел его только для «удобной» навигации по списку, т. е. если итератор установлен на end(), оператор ++ устанавливает его на begin(), а — на последний действительный элемент. Для разыменования используется поле _curr. Кликните здесь для просмотра всего текста
Сам код: Кликните здесь для просмотра всего текста
0 |
Комп_Оратор) 8852 / 4593 / 620 Регистрация: 04.12.2011 Сообщений: 13,718 Записей в блоге: 16 |
|
08.03.2019, 04:25 |
19 |
Как я догадываюсь Правильно догадываетесь.
1 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
08.03.2019, 04:25 |
Помогаю со студенческими работами здесь Ошибка компилятора Ошибка Компилятора в C++ ошибка компилятора Ошибка компилятора Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 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
-
Edited by
#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 для преобразования.