C++类型转换
C的所有强制类型转换(Type Cas t)都是:Type a = (Type)b
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。char b; int a = (int)b;
C++提供了四种类型转换,格式:Type a = static_cast<TYpe> (b)
- static_cast:静态类型转换,例如将char转换int
char a; int b = static_cast<int>(a);
- 除指针外的其他基础类型都能转换
- reinterpret_cast:重新解释类型,不同类型之间强制类型转换
char * a = "Hello C++"; int * b = NULL; *b = reinterpret_cast<int *>(a)
- reinterpret_cast不能用于转换基础类型
- dynamic_cast:动态类型转换 ,例如可以子类和父类之间多态类型转换(向下转)
class Animal {
public: virtual void capocity() = 0; }; class Pig :public Animal { public: virtual void capocity() { std::cout << "能吃能睡" << "\n"; } void pigMoney() { std::cout << "我能卖钱" << "\n"; } }; class Dog :public Animal { public: virtual void capocity() { std::cout << "捉耗子" << "\n"; } void digMeddling() { std::cout << "我能多管闲事" << "\n"; } }; void animalObj(Animal * animal) { animal->capocity(); Pig* pPig = dynamic_cast<Pig*>(animal);//dynamic_cast运行时进行类型识别(识别子类对象) //父类对象识别子类对象(向下识别) if (pPig != NULL) { pPig->pigMoney(); //使子类能过进行子类特有行为 } Dog* pDog = dynamic_cast<Dog*>(animal); if (pDog != NULL) { pDog->digMeddling(); } } int main() { Pig pg; Dog dg; animalObj(&pg); animalObj(&dg); system("pause"); return 0; }
- const_const:去除变量const属性(将只读属性 去除)
void buff(const char* p) {
char* pp = NULL;
pp = const_cast<char*>(p);// 将 * p的const属性去除,使其能够被修改
pp[0] = 'd';
}
int main()
{
char bbuff[] = "jhiogibh";//这就允许修改
const char* bbbuff = "hisvhiashvi";//向这类的就不允许修改
buff(bbuff);
buff(bbbuff);
system("pause");
return 0;
}
- 在使用const_const之前,要确保你说修改的内存空间允许修改,如果将不允许修改的内存修改,将造成很严重的后果,例如以下错误:

更多精彩