看下面代码 template <class T> class CDfgpRefCounter
{
public:
CDfgpRefCounter() { t = 0; }
CDfgpRefCounter(T *_t) { t = _t; if(t) t->ref(); }
CDfgpRefCounter( const CDfgpRefCounter &other ) { t = other.t; if(t) t->ref(); }
~CDfgpRefCounter(){ if(t) t->deref(); }
CDfgpRefCounter &operator =(T *_t){
if( _t ) _t->ref();
if( t ) t->deref();
t = _t;
return *this;
}
CDfgpRefCounter &operator =(const CDfgpRefCounter &other){
if( other.t ) other.t->ref();
if( t ) t->deref();
t = other.t;
return *this;
}
inline T *operator->() const { return t; }
inline operator T*() const { return t; }
private:
T *t;
};
CDfgpRefCounter<CDfgbScene> m_refScene; // 原场景处理 if( m_refScene ){ // 剥离原对象信号 disconnect( m_refScene, 0, this, 0); }
这里 if( m_refScene ) 就运用了 operator T*() 显示类型转换函数,把CDfgpRefCounter转换成了CDfgbScene*指针,下面一行disconnect中的也是一样。
类型转换函数的函数名(operator 目标类型)前不能指定返回类型,且没有参数。但在函数体最后一条语句一般为return语句,返回的是目标类型的数据。
下面再举一列: 1 #include "stdafx.h" 2 #include <iostream> 3 4 class Complex //复数类 5 { 6 private://私有 7 double real;//实数 8 double imag;//虚数 9 public: 10 Complex(double real,double imag) 11 { 12 this->real=real; 13 this->imag=imag; 14 } 15 Complex(double d=0.0)//转换构造函数 16 { 17 real=d;//实数取double类型的值 18 imag=0;//虚数取0 19 } 20 21 Complex operator+(Complex com1);//或friend Complex operator+(Complex com1,Complex com2); 22 operatordouble();//声明类型转换函数 23 void showComplex(); 24 }; 25 26 Complex Complex::operator+(Complex com1) 27 { 28 return Complex(real+com1.real,imag+com1.imag); 29 } 30 31 Complex::operatordouble()//定义类型转换函数 32 { 33 return real;//返回实数部分 34 } 35 36 void Complex::showComplex() 37 { 38 std::cout<<real; 39 if(imag>0) 40 std::cout<<"+"; 41 if(imag!=0) 42 std::cout<<imag<<"i"<<std::endl; 43 } 44 45 46 47 int main() 48 { 49 50 Complex com(10,10),sum; 51 sum=com+Complex(5.5);//Complex(5.5)把双精度数5.5转换为复数5.5+0i 52 sum.showComplex();//输出运算结果 53 54 double total; 55 total=double(com)+5.5;//double(com)把复数(10+10i)转换为双精度数10.0 56 std::cout<<"把Complex类对象转化为double类型与5.5相加为:"<<total; 57 58 return0; 59 } 结果: 3.最后对类型转换函数做几点补充:(1)类型转换函数只能作为类的成员函数,不能定义为类的友元函数;(2)类型转换函数中必须有return语句,即必须送回目标类型的数据作为函数返回值;(3)一个类可以定义多个类型转换函数,C++编译器会根据函数名来自动调用相应的类型转换函数函数;
|