1.标准数据之间会进行隐式类型安全转换,规则如下:
?在这里主要探讨c++中类类型与普通类型的转换:
1.类类型转换普通类型
class Fraction
{
public:
Fraction(int num,int den=1);
~Fraction();
//转换函数
/*
转换函数语法规则:
operator Type()
{
Type ret ;
........
return ret;
}
*/
operator double() const {
return (double)(m_Numerator*1.0 / m_Denominator);
}
private:
int m_Numerator;
int m_Denominator;
};
Fraction f(3, 5);
double d = 4 + f;//d=4.6
这里4+f,调用转换函数将f转换为0.6
2.普通类型转换为类类型(non-explicit-one-argument ctor)
class Fraction
{
public:
Fraction(int num,int den=1);
~Fraction();
Fraction operator+(const Fraction& f) {
return Fraction(this->m_Numerator * f.m_Denominator + this->m_Denominator * f.m_Numerator,
f.m_Denominator * this->m_Denominator);
}
private:
int m_Numerator;
int m_Denominator;
};
Fraction f(3, 5);
Fraction d = f + 4;//调用+运算符函数,4会转为Fraction(4,1),含有接受一个参数的构造函数,否则也无法转换
3.同时含有转换函数和可以隐式的调用构造函数(转换构造参数)会报错
class Fraction
{
public:
/*
转换构造函数:
-有仅有一个参数
-参数是基本类型
-参数是其它类型
*/
Fraction(int num,int den=1);
~Fraction();
operator double() const {
return (double)(m_Numerator*1.0 / m_Denominator);
}
Fraction operator+(const Fraction& f) {
return Fraction(this->m_Numerator * f.m_Denominator + this->m_Denominator * f.m_Numerator,
f.m_Denominator * this->m_Denominator);
}
private:
int m_Numerator;
int m_Denominator;
};
报错:? ?“Fraction::operator +”: 2 个重载有相似的转换? ? ,
所以在我们写构造函数都会使用关键字 explicit 防止类型隐式转换
class Fraction
{
public:
explicit Fraction(int num,int den=1);
~Fraction();
operator double() const {
return (double)(m_Numerator*1.0 / m_Denominator);
}
Fraction operator+(const Fraction& f) {
return Fraction(this->m_Numerator * f.m_Denominator + this->m_Denominator * f.m_Numerator,
f.m_Denominator * this->m_Denominator);
}
private:
int m_Numerator;
int m_Denominator;
};
Fraction f(3, 5);
Fraction d = f + 4;//报错:不存在从 "double" 转换到 "Fraction" 的适当构造函数
double d = f + 4;//可以,f转换
|