C++隐式转换与显式转换

来源:互联网 发布:网络创业的三个途径 编辑:程序博客网 时间:2024/06/05 14:59
普通类型的转换顺序:隐式把char——>int和从short——>double。转换可能会导致数据的丢失。
自定义类型:有两种函数可以进行隐式转换,单参数构造函数 和 隐式类型转换符。
自定义类型可以用函数前+ explicit 关键字,防止转换。

单个参数的构造函数,或可传单个参数的类构造函数
Example 1:
class things
{
   
public:
        things(
const std::string &name = ""):
              m_name(name),height(
0),weight(10){}
       
int CompareTo(const things & other);
        std::
string m_name;
       
int height;
       
int weight;
};
这里things的构造函数可以只用一个实参完成初始化。所以可以进行一个隐式转换,像下面这样:
things a;
................
//在这里被初始化并使用。
std::string nm = "book_1";
//由于可以隐式转换,所以可以下面这样使用
int result = a.CompareTo(nm); 
things xx = str; //这也会调用隐式转换

struct Month {
     Month(int m):val(m) {}
     int val;
};
Date(const Month& a);
Date(2);  //这样就调用了隐式转换
struct Month {
     explicit Month(int m):val(m) {}
     int val;
};
Date(2); //这样就会出错
Date(Month(2));   //必须这样

Example 2:
class Rational 
{                                   // 有理数类
public:

    Rational(int numerator = 0,     // 转换int到     
        int denominator = 1)       // 有理数类Rational
    {

    }
    Rational(Name name)             // 转换Name类型到 有理数类Rational
    {

    }
    Rational(string str)           // 转换string类型 到有理数类
    {

    }
};
char ch = 'a';
    string str;
    Name name(str);
   
    int i = 3;
  Rational ra;

    //以下均Right
  ra = i;          // 执行Rational(int numerator = 0,int denominator = 1)转换
    ra = ch;       //执行Rational(int numerator = 0,int denominator = 1)转换
    ra = str;      //执行Rational(string str)转转
  ra = name;     //执行Rational(Name name)转换

隐式类型转换运算符: 就是   operator 关键字,气候跟一个类型符号
class Rational 
{                                   // 有理数类
public:

    ……
    operator double() const           // 转换Rational类成 double类型
    {

    }

    operator string () const           // 转换Rational类成 string类型
    {

    }
};
   
str = ra;      // 执行operator string ()转换string 运行崩溃
i = 1*ra;     //执行operator double()转换成double型
cout<<ra;   //执行operator double() 转换成double型输出随机浮点数


google的c++规范中提到explicit的优点是可以避免不合时宜的类型变换,缺点无。所以google约定所有单参数的构造函数都必须是显示的,只有极少数情况下拷贝构造函数可以不声明称explicit。例如作为其他类的透明包装器的类。

effective c++中说:被声明为explicit的构造函数通常比其non-explicit兄弟更受欢迎。因为它们禁止编译器执行非预期(往往也不被期望)的类型 转换。除非我有一个好理由允许构造函数被用于隐式类型转换,否则我会把它声明为explicit。我鼓励你遵循相同的政策。 
0 0
原创粉丝点击