41-类型转换函数(上)

来源:互联网 发布:损坏文件修复软件 编辑:程序博客网 时间:2024/06/07 20:28

1、隐式转换规则

这里写图片描述

#include <iostream>#include <string>using namespace std;int main(){       short s = 'a';    unsigned int ui = 1000;    int i = -2000;    double d = i;    cout << "d = " << d << endl;    cout << "ui = " << ui << endl;    cout << "ui + i = " << ui + i << endl;    if( (ui + i) > 0 )//进行隐式类型转换int i——》unsigned int(有符号转无符号)    {        cout << "正数" << endl;    }    else    {        cout << "负数" << endl;    }    //short->int,char->int    cout << "sizeof(s + 'b') = " << sizeof(s + 'b') << endl;    return 0;}d = -2000ui = 1000ui + i = 4294966296正数sizeof(s + 'b') = 4

2、

这里写图片描述
可以

3、转换构造函数

这里写图片描述

4、

这里写图片描述

5、普通类型转换为类类型

这里写图片描述

6、

这里写图片描述

#include <iostream>#include <string>using namespace std;class Test{    int mValue;public:    Test()    {        mValue = 0;    }    explicit Test(int i)//防止编译器隐式转换    {        mValue = i;    }    Test operator + (const Test& p)    {        Test ret(mValue + p.mValue);        return ret;    }    int value()    {        return mValue;    }};int main(){       Test t;    //t = 5; 编译器会进行隐式转换 t = (Test)5;其实调用的是转换构造函数(就是构造函数)t = Test(5);        t = static_cast<Test>(5);    // t = Test(5); C++编译器提供的强制转换函数       Test r;    //r = t + 10;    r = t + static_cast<Test>(10);   // r = t + Test(10);    cout << r.value() << endl;    return 0;}

7、

这里写图片描述

8、

这里写图片描述

原创粉丝点击