C++的类型转换

C++的类型转换

1)static_cast<>() 静态类型转换,编译的时c++编译器会做类型检查;
基本类型能转换 但是不能转换指针类型
2)若不同类型之间,进行强制类型转换,用reinterpret_cast<>() 进行重新解释
3)一般性结论:
C语言中 能隐式类型转换的,在c++中可用 static_cast<>()进行类型转换。因C++编译器在编译检查一般都能通过;
C语言中不能隐式类型转换的,在c++中可以用 reinterpret_cast<>() 进行强行类型 解释。总结:static_cast<>()和reinterpret_cast<>() 基本上把C语言中的 强制类型转换给覆盖
reinterpret_cast<>()很难保证移植性。
4)dynamic_cast<>(),动态类型转换,安全的基类和子类之间转换;运行时类型检查
5)const_cast<>(),去除变量的只读属性

#include <iostream>
using namespace std;


#if 0
int main1() {

	double dpi = 3.1415926;
	int num1 = (int)dpi;//c风格的类型转换
	int num2 = static_cast<int>(dpi);//c++风格的类型转换,编译时c++编译器会做类型检查
	//int num3 = dpi;//C语言中的隐式类型转换的地方,全都可以使用static_cast<>()

	cout<<"hello....."<<endl;
	system("pause");
	return 0;
}

//定义一个动物类型
class Animal {
public:
	virtual void cry() = 0;
private:
};
class Dog :public Animal {
public:
	virtual void cry() {
		cout << "汪汪" << endl;
	}
	void DoHome() {
		cout << "狗可以看家" << endl;
	}
private:
};
class Cat :public Animal {
public:
	virtual void cry() {
		cout << "喵喵" << endl;
	}
	void DoNothing() {
		cout << "猫会抓老鼠" << endl;
	}
private:
};

void Print(Animal* base) {
	base->cry();//多态发生的条件,虚函数重写,有继承,父类指针指向子类对象

	//dynamic_cast可以把父类对象转换成子类对象,
	//向下转型  把老子转为小子
	Dog* dog = dynamic_cast<Dog*>(base);
	if (dog != NULL) {
		dog->DoHome();
	}
	Cat* cat = dynamic_cast<Cat*>(base);
	if (cat != NULL) {
		cat->DoNothing();
	}

}
int main2() {
	Dog d1;
	Cat c1;
	Print(&d1);
	Print(&c1);
	system("pause");
	return 0;
}
#endif
//const char*修饰让形参具有了只读属性
void Print(const char*myp) {
	cout << myp << endl;
	char* p = NULL;
	//const_cast只是把只读属性去掉
	p = const_cast<char*>(myp);
	//通过指针修改这个空间的值
	p[0] = 'A';
	cout << p << endl;
}
int main() {

	const char *buf = "helloweihang";//指针指向的是只读空间
	char* p1 = const_cast<char*>(buf);//去除只读属性
	//p1="aaaa"   err
	char myp[13] = "helloweihang";
	Print(myp);
	system("pause");
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值