1.标准数据之间会进行隐式类型安全转换,规则如下:
在这里主要探讨c++中类类型与普通类型的转换:
1.类类型转换普通类型
class Fraction
{
public:
Fraction(int num,int den=1);
~Fraction();
//转换函数
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转换
到此这篇关于C++ 转换函数用法案例详解的文章就介绍到这了,更多相关C++ 转换函数用法内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!