隐式转换

随便举几个例子。。。

1
2
3
4
int a = 3.14; // a = 3
// 指针转换,C 样式数组将隐式转换为指向该数组中的第一个元素的指针
// +3 后指针指向p
char *s = "Help" + 3;

显示转换

C 样式的强制类型转换

1
2
(int) x;
in(x);

建议 使用 C++ 强制转换运算符,它们更加类型安全,并且更加明确地表达编程目的

static_cast

static_cast,用于仅在编译时检查的强制转换。 如果编译器检测到尝试在完全不兼容的类型之间强制转换,static_cast 将返回错误。还可以使用它在指向基对象的指针和指向派生对象的指针之间强制转换,但编译器无法总是判断出此类转换在运行时是否安全

1
2
3
4
5
6
7
8
9
10
11
12
double d = 1.58947;
int i = d; // warning C4244 possible loss of data
int j = static_cast<int>(d); // No warning.
string s = static_cast<string>(d); // Error C2440:cannot convert from
// double to std:string

const char *c = "qwt";
string s = static_cast<string>(c);

// No error but not necessarily safe.
Base* b = new Base();
Derived* d2 = static_cast<Derived*>(b);

对于编译器不能完成自动转换的,static_cast 就能帮忙完成转换

1
2
3
void* p = &d; // ok: address of any nonconst object can be stored in a void* 
// ok: converts void* back to the original pointer type
double *dp = static_cast<double*>(p);

const_cast

const 转换成非 const,只能改变 low-level const

1
2
const char *pc;
char *p = const_cast<char*>(pc); // ok: but writing through p is undefined

dynamic_cast

用于从指向基对象的指针到指向派生对象的指针的、安全且经过运行时检查的强制转换

dynamic_cast 在向下转换方面比 static_cast 更安全,但运行时检查会产生一些开销

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Base* b = new Base();

// Run-time check to determine whether b is actually a Derived*
Derived* d3 = dynamic_cast<Derived*>(b);

// If b was originally a Derived*, then d3 is a valid pointer.
if(d3)
{
// Safe to call Derived method.
cout << d3->DoSomethingMore() << endl;
}
else
{
// Run-time check failed.
cout << "d3 is null" << endl;
}

//Output: d3 is null;

reinterpret_cast

此强制转换运算符不像其他运算符一样常用,并且不能保证可将其移植到其它编译器。