什么是转换构造函数 [英] What are the conversion constructors
问题描述
class Complex
{
private:
double real;
double imag;
public:
//默认构造函数
复杂(double r = 0.0,double i = 0.0):real(r),imag(i){}
//与复数比较的方法
bool operator ==(Complex rhs){
return(real == rhs.real& imag == rhs.imag)?真假;
}
};
int main()
{
// a复杂对象
复杂com1(3.0,0.0);
if(com1 == 3.0)
cout<< 相同;
else
cout<< 不一样;
return 0;
}
输出:
相同
为什么这段代码给出的输出为Same,转换构造函数在这里工作,请解释,许多感谢提前
转换构造函数是任何非 - 显式
构造函数,可调用一个参数。在您的代码示例中,由于 Complex
构造函数为其参数提供了默认值,因此可以使用单个参数调用(例如 3.0
)。因为这个构造函数没有标记为 explicit
,那么它是一个有效的转换构造函数。
c $ c> com1 == 3.0 - 因为没有运算符==
复杂
和 double
- 调用转换构造函数。所以你的代码等价于这样:
if(com1 == Complex(3.0))
class Complex
{
private:
double real;
double imag;
public:
// Default constructor
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// A method to compare to Complex numbers
bool operator == (Complex rhs) {
return (real == rhs.real && imag == rhs.imag)? true : false;
}
};
int main()
{
// a Complex object
Complex com1(3.0, 0.0);
if (com1 == 3.0)
cout << "Same";
else
cout << "Not Same";
return 0;
}
Output: Same
Why this code gives output as Same, how the conversion constructor in working here, please explain, Many many thanks in advance
A conversion constructor is any non-explicit
constructor callable with one argument. In your code sample, as the Complex
constructor provides default values for its parameters, it can be called with a single argument (say 3.0
). And since such constructor is not marked explicit
, then it is a valid conversion constructor.
When you do com1 == 3.0
--given that there is no operator ==
between Complex
and double
-- a conversion constructor is invoked. So your code is equivalent to this:
if( com1 == Complex(3.0) )
这篇关于什么是转换构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!