2011年计算机二级C++实例编程辅导8

考试站(www.examzz.com)   【考试站:中国教育考试第一门户】   2011年11月10日

  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


首页 1 2 3 4 5 尾页

相关文章