[C++再学习系列] 隐式类型转换与转换操作符operator T

[C++再学习系列] 隐式类型转换与转换操作符operator T

分类: C++再学习系列 2009-07-05 21:26 217人阅读 评论(0) 收藏 举报
 
 
http://blog.csdn.net/zhenjing/article/details/4323615
 
 
http://topic.csdn.net/t/20050301/13/3815012.html   //good discusion!

隐式类型转换与转换操作符 operator T

C++ 标准允许隐式类型转换,即对特定的类,在特定条件下,某些参数或变量将隐形转换成类对象 ( 创建临时对象 ) 。如果这种转换代价很大 ( 调用类的构造函数 ) ,隐式转换将影响性能。

隐式转换的发生条件:函数调用中,当参数类型不匹配,如果隐式转换后能满足类型匹配条件,编译器将启用类型转换。

控制隐式类型转换的两种途径:

1) 减少函数调用的参数不匹配情况:提供签名 ( 函数参数类型 ) 与常见参数类型的精确匹配的重载函数。

2) 限制编译器的启用隐式转换:使用 explicit 限制的构造函数和具名转换函数。

 

下面的例子将导致隐式类型转换:

1) 未限制的构造函数:

class Widget { // …

  Widget( unsigned int widgetizationFactor );

  Widget( const char* name, const Widget* other = 0 );

};

2) 转换操作符 ( 定义成 operator T() ,其中 T 为 C++ 类型 )

class String {

public:

    operator const char*();  // 在需要情况下, String 对象可以转成 const char* 指针。

};

 

上面的定义将使很多愚蠢的表达式通过编译 ( 编译器启用了隐式转换 ) 。

Assume s1, s2 are Strings:

int x = s1 - s2;                // compiles; undefined behavior

const char* p = s1 - 5;         // compiles; undefined behavior

p = s1 + '0';                 // compiles; doesn't do what you'd expect

if( s1 == "0" ) { ...}          // compiles; doesn't do what you'd expect

 

合理的解决方案:

By default, write explicit on single-argument constructors:

默认时,为单参数 的构造函数加上 explicit :

class Widget { // …

  explicit Widget( unsigned int widgetizationFactor );

  explicit Widget( const char* name, const Widget* other = 0 );

};

 

使用提供的转换具名函数代替转换操作符:

Use named functions that offer conversions instead of conversion operators:

class String { // …

  const char* as_char_pointer() const;       // in the grand c_str tradition

};

 

 

 

隐式类型转换可以使用构造函数以及但参数的构造函数
class type
{
int a;
public:
type (int b) {
a = b;
}
};

main ()
{
type c = 123; //在此调用的是type的构造函数,自动转换类型。不过只有在初始化对象时才可以
}
在函数调用中也行

void fun(type a)
{

}

main ()
{
fun (123); //并没有错误,不过一个前提是函数的形参必须是传值调用而不能引用,并且没有参数为int类型的重载函数,否则会调用参数为int的函数(涉及到候选函数问题)
}

posted @ 2011-11-29 11:55  rookieeeeee  阅读(2774)  评论(0编辑  收藏  举报