转换函数 是用来将 类类型 转化成 某种特定类型
格式:operator typename();
注意
①转换函数必须是类方法
②没有任何参数
③不能指定返回类型
例子
operator int () const;
operator double () const;
#ifndef __TIME_H__
#define __TIME_H__
class TIME
{
private:
int nHours;
int nMinutes;
double Test;
public:
TIME();
TIME(int H, int M);
TIME(int H);
TIME(double test);
void SetTime(int H, int M);
void ShowTime(void) const;
TIME operator+(const TIME & t) const;
TIME operator*( double b) const;
friend TIME operator*(double b, const TIME & t);
operator int () const;
operator double () const;
};
#endif
TIME::operator int () const
{
std::cout<<"这是int 的转换函数"<<std::endl;
return nHours;
}
TIME::operator double () const
{
std::cout<<"double 的转换函数 "<<std::endl;
return Test;
}
int main(int argc, char* argv[])
{
TIME a;
int nNum;
double dNum;
std::cout<<&a<<std::endl;
a = 10;
nNum = int(a);
std::cout<<&a<<" "<<nNum<<std::endl;
TIME b = 3.14;
dNum = b ;
std::cout<<&b<<" "<<dNum<<std::endl;
return 0;
}
如果只写了一个转化函数,可以使用
std::cout<<a<<std::endl; 直接输出
但如果写了两个及以上,会产生二义性错误。