就业数据资源平台
当前位置:首页 > C++语言程序设计
2012年计算机等级二级C++辅导实例编程(8)

 C++重载类型转换操作符(type cast operator)

  boost::ref和boost::cref使用了重载“类型转换(type cast)”操作符来实现使用引用类型来替换模版参数,本文就介绍一下这种操作符的重载方法。


  函数原型


  T1::operator T2() [const];   //T1的成员函数,重载"(T2)a"操作符


  1. 类型转换重载函数的返回值是隐含的,并且不能显示声明,返回值是与转换的类型相同的,即为上面原型中的T2。


  2. 不能有参数;


  3. 支持继承,可以为虚函数;


  4. 支持使用typedef定义的类型;


  先通过一个简单的例子来说明如何使用类型转换重载


  1 #include


  2


  3 class D {


  4 public:


  5 D(double d) : d_(d) {}


  6


  7 /* 重载“(int)D” */


  8 operator int() const {


  9 std::cout << "(int)d called!" << std::endl;


  10 return static_cast(d_);


  11 }


  12


  13 private:


  14 double d_;


  15 };


  16


  17 int add(int a, int b) {


  18 return a + b;


  19 }


  20


  21 int main() {


  22 D d1 = 1.1;


  23 D d2 = 2.2;


  24 std::cout << add(d1, d2) << std::endl;


  25


  26 return 0;


  27 }


  28


  29


  在24行执行add(d1,d2)函数时“(int)D”重载函数将被调用,程序运行的输出为:


  (int)d called!


  (int)d called!


  3


  类型转换操作符 vs 类型转换构造函数(conversion constructor)


  有时候使用conversion constructor就能实现类型转换,这种方式效率更高而且也更直观,下面举例说明:


  1 #include


  2


  3 class A


  4 {


  5 public:


  6 A(int num = 0) : dat(num) {}


  7


  8 /* 重载"(int)a" */


  9 operator int() { return dat; }


  10


  11 private:


  12 int dat;


  13 };


  14


  15


  16 class X


  17 {


  18 public:


  19 X(int num = 0) : dat(num) {}


 


 20

  21 /* 重载"(int)a" */


  22 operator int() { return dat; }


  23


  24 /* 重载"(A)a" */


  25 operator A() {


  26 A temp = dat;


  27 return temp;


  28 }


  29


  30 private:


  31 int dat;


  32 };


  33


  34


  35 int main()


  36 {


  37 X stuff = 37;


  38 A more = 0;


  39 int hold;


  40


  41 hold = stuff; // convert X::stuff to int


  42 std::cout << hold << std::endl;


  43


  44 more = stuff; // convert X::stuff to A::more


  45 std::cout << more << std::endl; // convert A::more to int


  46


  47 return 0;


  48 }


  49


上面这个程序中X类通过重载“operator A()”来实现将X类型对象转换成A类型,这种方式需要先创建一个临时A对象再用它去赋值目标对象;更好的方式是为A类增加一个构造函数:

  A(const X& rhs) : dat(rhs) {}


  同时,请注意上面程序的第45行more的类型在调用std::cout时被隐式地转成了int!


  一个简单boost::ref实现


  通过重载type cast operator,我们就可以自己实现一个简版的boost::ref。


  1 #include


  2


  3 template


  4 class RefHolder


  5 {


  6 public:


  7 RefHolder(T& ref) : ref_(ref) {}


  8


  9 /* 重载“(T&)A”操作符 */


  10 operator T& () const {


  11 return ref_;


  12 }


  13


  14 private:


  15 T& ref_;


  16 };


  17


  18


  19 template


  20 inline RefHolder ByRef(T& t) {


  21 return RefHolder(t);


  22 }


  23


  24 int inc(int& num) {


  25 num++;


  26 return num;


  27 }


  28


  29


  30 int main() {


  31 int n = 1;


  32 std::cout << inc(ByRef(n)) << std::endl; //RefHolder被转换成了"int&"类型


  33


  34 return 0;


  35 }

就业数据资源平台