Возьмите это в качестве примера:
class complexNumbers {
double real, img;
public:
complexNumbers() : real(0), img(0) { }
complexNumbers(const complexNumbers& c) { real = c.real; img = c.img; }
complexNumbers(double r, double i = 0.0) { real = r; img = i; }
friend void display(complexNumbers cx);
};
void display(complexNumbers cx){
cout<<"Real Part: "<<cx.real<<" Imag Part: "<<cx.img<<endl;
}
int main() {
complexNumbers one(1);
display(one);
display(300); //This code compiles just fine and produces the ouput Real Part: 300 Imag Part: 0
return 0;
}
С метод display
ожидает объект/экземпляр класса complexNumbers
в качестве аргумента, когда мы передаем десятичное значение 300, неявное преобразование происходит на месте.
Чтобы преодолеть эту ситуацию, мы должны заставить компилятор создать объект, используя только явную конструкцию, как указано ниже:
explicit complexNumbers(double r, double i = 0.0) { real = r; img = i; } //By Using explicit keyword, we force the compiler to not to do any implicit conversion.
и после этого constructor
присутствует в вашем классе, оператор display(300);
даст ошибка.
@VictorПолевой конструкторы, а не конверсия. ;) –
@RobinKrahl oops :) Удалено. –
Вы думаете об этом? [Что означает явное ключевое слово в C++?] (Https://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-in-c-mean/121163) – Csq