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 = -2000
ui = 1000
ui + 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;
}