C++类型转换
第六章 C++类型转换6.1 静态转换(static_cast)6.2 动态转换(dynamic_cast)6.3 常量转换(const_cast)6.4 重新解释转换(reinterpret_cast)
第六章 C++类型转换
类型转换(cast)是将一种数据类型转换成另一种数据类型。例如,如果将一个整型值赋给一个浮点类型的变量,编译器会暗地里将其转换成浮点类型。
转换是非常有用的,但是它也会带来一些问题,比如在转换指针时,我们很可能将其转换成一个比它更大的类型,但这可能会破坏其他的数据。
应该小心类型转换,因为转换也就相当于对编译器说:忘记类型检查,把它看做其他的类型。
一般情况下,尽量少的去使用类型转换,除非用来解决非常特殊的问题。
无论什么原因,任何一个程序如果使用很多类型转换都值得怀疑.
标准c++提供了一个显示的转换的语法,来替代旧的C风格的类型转换。
使用C风格的强制转换可以把想要的任何东西转换成我们需要的类型。那为什么还需要一个新的C++类型的强制转换呢?
新类型的强制转换可以提供更好的控制强制转换过程,允许控制各种不同种类的强制转换。C++风格的强制转换其他的好处是,它们能更清晰的表明它们要干什么。程序员只要扫一眼这样的代码,就能立即知道一个强制转换的目的。
6.1 静态转换(static_cast)
用于类层次结构中基类(父类)和派生类(子类)之间指针或引用的转换。 ○ 进行上行转换(把派生类的指针或引用转换成基类表示)是安全的; ○ 进行下行转换(把基类指针或引用转换成派生类表示)时,由于没有动态类型检查,所以是不安全的。用于基本数据类型之间的转换,如把int转换成char,把char转换成int。这种转换的安全性也要开发人员来保证。
class Animal
{};
class Dog
: public Animal
{};
class Other
{};
void test01(){
char a
= 'a';
double b
= static_cast
<double>(a
);
}
void test02(){
Animal
* animal01
= NULL;
Dog
* dog01
= NULL;
Animal
* animal02
= static_cast
<Animal
*>(dog01
);
Dog
* dog02
= static_cast
<Dog
*>(animal01
);
}
void test03(){
Animal ani_ref
;
Dog dog_ref
;
Animal
& animal01
= ani_ref
;
Dog
& dog01
= dog_ref
;
Animal
& animal02
= static_cast
<Animal
&>(dog01
);
Dog
& dog02
= static_cast
<Dog
&>(animal01
);
}
void test04(){
Animal
* animal01
= NULL;
Other
* other01
= NULL;
}
6.2 动态转换(dynamic_cast)
dynamic_cast主要用于类层次间的上行转换和下行转换;在类层次间进行上行转换时,dynamic_cast和static_cast的效果是一样的;在进行下行转换时,dynamic_cast具有类型检查的功能,比static_cast更安全;
class Animal
{
public
:
virtual
void ShowName() = 0;
};
class Dog
: public Animal
{
virtual
void ShowName(){
cout
<< "I am a dog!" << endl
;
}
};
class Other
{
public
:
void PrintSomething(){
cout
<< "我是其他类!" << endl
;
}
};
void test01(){
int a
= 10;
}
void test02(){
Animal
* animal01
= NULL;
Dog
* dog01
= new Dog
;
Animal
* animal02
= dynamic_cast
<Animal
*>(dog01
);
animal02
->ShowName();
}
void test03(){
Dog dog_ref
;
Dog
& dog01
= dog_ref
;
Animal
& animal02
= dynamic_cast
<Animal
&>(dog01
);
animal02
.ShowName();
}
void test04(){
Animal
* animal01
= NULL;
Other
* other
= NULL;
}
6.3 常量转换(const_cast)
该运算符用来修改类型的const属性。。
常量指针被转化成非常量指针,并且仍然指向原来的对象;常量引用被转换成非常量引用,并且仍然指向原来的对象;
注意:不能直接对非指针和非引用的变量使用const_cast操作符去直接移除它的const.
void test01(){
const int* p
= NULL;
int* np
= const_cast
<int*>(p
);
int* pp
= NULL;
const int* npp
= const_cast
<const int*>(pp
);
const int a
= 10;
void test02(){
int num
= 10;
int & refNum
= num
;
const int& refNum2
= const_cast
<const int&>(refNum
);
}
6.4 重新解释转换(reinterpret_cast)
这是最不安全的一种转换机制,最有可能出问题。
主要用于将一种数据类型从一种类型转换为另一种类型。它可以将一个指针转换成一个整数,也可以将一个整数转换成一个指针.