конструктор для объекта obj() не определён
Интерпретируется как декларация функции.
Мдя действительно работает. Непонятно. я ж по умолчанию определил значения. Спасибо.
Интерпретируется как декларация функции.
У меня есть следующая проблема:
предположим, что я пытаюсь реализовать свой собственный класс MyInt, который способен хранить большие числа (я знаю о реализации BigNum — это просто практика). Я реализовал конструкторы, которые принимают int, unsigned long, unsigned long long и т. Д. — отсюда мой вопрос.
Я пытаюсь перегрузить оператор + с помощью следующего объявления:
Он отлично работает, когда я добавляю в MyInt, однако я хотел бы, чтобы он работал в таких случаях, как
Когда я называю это так, я получаю следующий вывод:
Буду признателен за любые предложения о том, как решить эту проблему
Редактировать:
Вот пример кода, написанный мной. Конструктор явный
Решение
Конструкция explicit , означает неявное преобразование из int в MyInt не допускается, а затем operator+(const MyInt &, const MyInt &) не может быть применено для вызова MyInt + int ,
Solution1
Добавить перегрузочную версию operator+ , такие как:
Solution2
Удалить explicit от конструктора.
Другие решения
Учитывая следующую проблему:
… Разумным решением является сделать неявный конструктор преобразования, т.е. explicit ,
Например, std::string позволяет построить std::string неявно из буквального. Это обеспечивает большую практическую выгоду. Но тогда нет проблем с s + s потому что нет встроенного + для аргументов указателя, и std::string не обеспечивает неявное преобразование обратно в char const* ,
Тем не менее, я думаю, что неявное преобразование в класс большого числа имеет смысл. Сделайте обратное преобразование во встроенный тип, explicit (если это неявно, то эта проблема снова появляется). И желательно по имени.
Решение состоит в том, чтобы добавить operator+(const MyInt & lhs, int rhs);
Другое решение состоит в том, чтобы добавить MyInt(int) конструктор, который затем неявно вызывается компилятором.
I’v read several posts here about this kind of errors, but I wasn’t able to solve this one. Has soon I define the operator int and the function f, fails to compile. I tested several things by I wasn’t able to solve the issue. Thanks

3 Answers 3
You don’t seem to have posted the code that actually causes the error. I guess it looks something like
The problem is that your class allows implicit conversions both to and from int ; so a + 4 could be either
with no reason to choose one over the other. To resolve the ambiguity, you could either:
- make the conversion explicit, as above; or
- declare either the constructor or the conversion operator (or even both) explicit so that only one (or even neither) conversion can be done implicitly.
You have several options to fix your problem:
-
Forbid implicit conversion from int to Fraccao : Make the constructor explicit .
Forbid implicit conversion from Fraccao to int : Make the conversion operator explicit .
Convert manually on the callers side, given Fraccao f; int i; either int(f)+i or f+Fraccao(i) .
Provide additional overloads to resolve the ambiguity:
The latter probably means you also want:
And finally, if you want the latter, you can use libraries like Boost.Operators or my df.operators to support you and avoid writing the same forwarders over and over again.
The compiler sees two ways to interpret a + 4 . It can convert the 4 to an object of type Fraccao and use operator+(const Fraccao&, const Fraccao&) or it can convert a to type int with the member conversion operator, and add 4 to the result. The rules for overloading make this ambiguous, and that’s what the compiler is complaining about. In general, as @gx_ said in a comment, this problem comes up because there are conversions in both directions. If you mark the operator int() with explicit (C++11) the code will be okay.