码迷,mamicode.com
首页 > 其他好文 > 详细

转换操作符(conversion operator)

时间:2015-05-27 22:45:28      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

转换操作符(conversion operator) 是一种特殊的类成员函数。它定义将类类型值转变为其它类型值的转换。

 1 classSmallInt
 2 {
 3 public:
 4     SmallInt(int i =0): val(i)
 5     {
 6         if( i <0|| i >255)
 7         throw std::out_of_range("Bad SmallInt initializer");
 8     }
 9     operatorint()const {return val;}
10 private:
11     std::size_t val;
12 };        

 

转换函数采用如下通用形式:
operator type();
这里,type表示内置类型名、类型型名或由类型名所定义的名字。对任何可作为函数返回类型的类型(除void 外)都可以定义转换函数。
一般而言,不允许转换为数组或函数类型(congnima:数组名是常量),转换为指针类型(数据和函数指针)以及引用类型是可以的。
 
注释:转换函数必须是成员函数,不能指定返回类型,并且形参表必须为空。
 
 

1.使用类类型转换


只要存在转换,编译器将在可以使用内置转换的地方自动调用它:
  • 在表达式中:
    1 SmallInt si;
    2 double dval;
    3 si >= dval;//si converted to int and then convert to double

     

     
  • 在条件中:
    1 if(si)//si converted to int and then convert to bool

     

  • 将实参传给函数或从函数返回值:
    1 int calc(int);
    2 SmallInt si;
    3 int i = calc(si);//convert si to int and call calc

     

  • 作为重载操作符的操作数:
    1 //convert si to int then call operator << on the int value
    2 cout << si << endl;

     

  • 在显式类型转换中:
    1 int ival;
    2 SmallInt si =3.541;//constructor
    3 //instruct compiler to cast si to int
    4 ival =static_cast<int>(si)+3;

     

2.类类型转换和标准转换

使用转换函数时,被转换的类型不必与所需要的类型完全匹配。必要时可在类类型转换之后跟上标准转换以获得想要的类型。
1 SmallInt si;
2 double dval;
3 si >= dval;// si converted to int and then convert to double

 

3.标准转换可放在类类型转换之前

1 void calc(SmallInt);
2 short sobj;
3 //sobj promoted from short to int
4 //that int converted to SmallInt through the SmallInt(int) constructor
5 calc(sobj);

 

 





转换操作符(conversion operator)

标签:

原文地址:http://www.cnblogs.com/codetravel/p/4534547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!