C++强制类型转换

C++的强制类型转换具有如下形式:

cast-name <type>(expression);

cast-name是static_cast  dynamic_cast  const_cast  reinterpret_cast 中的一种。

 

static_cast:基本的数据类型转换(类似于C中的自动类型转换)

例:将double型强转成int型

double a = 3.1415;
int b = static_cast<int>(a);

不适用于指针类型: 

int a = 3;
char *p = static_cast<char *>(&a);//error

但是,父子类指针之间相互转换是可以的 

reinterpret_cast:提供较低层次的重新解释(类似C中的强制类型转换)

例:可以将指针类型进行强制类型转换

int a = 3;
char *p = reinterpret_cast<char *>(&a);

dynamic_cast:运行时类型识别 RTTI

将父类指针转换为子类指针,如果失败,返回NULL;

#include <iostream>
using namespace std;

class point {
public:
	point(int x = 0, int y = 0) {
		this->x = x;
		this->y = y;
	}
public:
	virtual void print() {
		cout << x << " " << y;
	}
private:
	int x;
	int y;
};
class circle:public point {
public:
	circle(int x=0, int y=0, int r=0) :point(x, y) {
		this->r = r;
	}
public:
	virtual void  print() {
		cout <<r;
	}
private:
	int r;
};

void test(point *p) {
	//p->print();
	circle *c = dynamic_cast<circle *>(p);
	if (c) {
		c->print();
	}
}

int main() {
	point p1(1,2);
	circle c1(1,2,3);
	test(&p1);
	test(&c1);
	system("pause");
}

const_cast:去除变量的只读属性

void change(const char *p) {
	char *p1 = const_cast<char *>(p);
	strcpy(p1, "asdfasdfasd");
}

int main() {
	char s[20] = "abcd";
	change(s);
	cout << s;
	system("pause");
}

如果p1所指空间的属性为只读,那么程序会出错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值