C++ 显式和隐式构造函数
我读过很多关于stackoverflow的问题,涉及隐式和显式构造函数,但是我仍然难以区分隐式和显式构造函数C++ 显式和隐式构造函数,c++,constructor,C++,Constructor,我读过很多关于stackoverflow的问题,涉及隐式和显式构造函数,但是我仍然难以区分隐式和显式构造函数 我想知道是否有人能给我一个很好的定义和一些例子,或者可以指导我找到一本能很好地解释这个概念的书/参考资料举个例子: class complexNumbers { double real, img; public: complexNumbers() : real(0), img(0) { } complexNumbers(const comple
我想知道是否有人能给我一个很好的定义和一些例子,或者可以指导我找到一本能很好地解释这个概念的书/参考资料举个例子:
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;
}
在这个构造器出现在你的类中之后,语句显示300;将给出一个错误。@VictorPolevoy构造函数,而不是转换@RobinKrahl oops:删除了。你在考虑这个吗?人们只会发布你在stackoverflow上的许多问题上已经可以得到的相同信息……如果你读到的内容没有被理解,那么就询问一些关于混乱部分的具体问题。。。。
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.