使用operator实现的类型转换与函数对象
C++中可以定义一个类的成员函数来对类进行转换,形式如下:
operator Type ();
函数对象: 通过重载(),让一个类具备了函数的功能,形式如下:
Type operator(param1,param2);
下面是一个例子:
#include <iostream>
using std::cout;
using std::endl;
template<class x1, class x2> class Add{
public:
Add(){}
Add(x1 num1,x2 num2):m_num1(num1),m_num2(num2){ }
// 转换函数
operator x1(){return (m_num1 + (x1)m_num2); }
//函数对象
x1 operator()(x1 num1,x2 num2){return (num1 + (x1)num2);}
private:
x1 m_num1;
x2 m_num2;
};
template<class x>class A{
public:
A(x t):m_num(t){}
operator x(){return m_num;}
private:
x m_num;
};
int _tmain(int argc, _TCHAR* argv[])
{
cout<< Add<int,double>()(A<int>(2),A<double>(4.2))<<endl;
Add<double,int> g( A<double>(4.2),A<int>(2));
cout<<g<<endl;
getchar();
return 0;
}