转换函数用于将自定义类型转换为基本类型
转换函数是类成员,没有参数,没有返回类型,名为operator typeName();将类对象赋给typeName变量或者将其强制转换为typeName类型时,对应的转换函数将被调用;
#include<iostream>
using std::cout;
class body
{
private:
double m_height;
public:
operator int () const;//转换函数
body(double height);
};
body::operator int () const
{
return m_height;
}
body::body(double height)
{
m_height=height;
}
int main()
{
body wwj=178.8;
double p=wwj;//隐式转换
cout<<p;
cout<<double(wwj);//显式转换
return 0;
}
如果只定义了唯一一个int转换函数,但是要将自定义类型转换为基本类型,也是可以的
原则上最好使用显示转换,避免隐式转换
C++98中,关键字explicit 不能用于转换函数,但C++11中消除了这种限制,在C++11中可以将转换运算符声明为显示的,
class Stonewt
{
explicit operator int() const;
explicit operator double() const;
};
有了这些声明,需要强制转换时将用到这些运算符
另一种方法是用一个功能相同的非转换函数替换转换函数,也就是可以将
Stonewt::operator int() {return int (pounds+0.5);}
替换为:
int Stonewt::Stone_to_Int() {return int(pounds+0.5);}
int plb=poppins.Stone_to_Int();