第三十九节 C++ 类型转换运算符 static_cast, dynamic_cast, reinterpret_cast, const_cast

本文介绍了C++中的四种类型转换运算符:static_cast用于静态类型转换,dynamic_cast用于运行时类型检查和转换,reinterpret_cast用于底层位级别的转换,而const_cast则用于添加或去除对象的const或volatile属性。通过示例展示了它们在实际中的应用。
摘要由CSDN通过智能技术生成
C++类型转换运算符:static_cast, dynamic_cast, reinterpret_cast, const_cast

使用格式: dest_type result = cast_type<dest_type> (objest_to_be_casted)

static_cast:  用途1: 在继承中,在编译阶段检查转换类型是否相关,若不相关,编译失败,可用于继承类的向上转换
                   用途2: 显示提醒程序员,这里进行了类型转换, int num = static_cast<int>(value);

dynamic_cast: 在运行阶段,检查转换类型是否相关,用于继承类的向下转换,可检测使用基类参数的对象,是否为此基类的派生类,若不是,返回NULL,用dynamic_cast时一定要检查返回的地址是否为NULL

reinterpret_cast: 强制类型转换

const_cast: 去除const限制

#include <iostream>
using namespace std;

class  Base {
public:
	/*实现多态*/
	virtual void getVesion() {
		cout << "The Base class getVesion()" << endl;
	}

	Base() { cout << "Base() constructor" << endl; }

	/*防止仅释放基类*/
	virtual	~Base() { cout << "~Base() deconstructor" << endl; }

};

class Derived : public Base {
public:
	void getVesion() {
		cout << "The Derived getVesion()" << endl;
	}

	Derived() {
		cout << "Detived() constrctor" << endl;
	}

	~Derived() { 
		cout << "~Detived() deconstrctor" << endl; 
		delete this;
	}
};

class Derived2 : public Base {
public:
	void getVesion() {
		cout << "The Derived2 getVesion()" << endl;
	}

	Derived2() {
		cout << "Detived2() constrctor" << endl;
	}

	~Derived2() {
		cout << "~Detived2() deconstrctor" << endl;
		delete this;
	}
};


class NotDerived {
public:
	void getVesion() {
		cout << "The NotDerived getVesion()" << endl;
	}

	NotDerived() {
		cout << "NotDerived() constrctor" << endl;
	}

	~NotDerived() {
		cout << "~NotDerived() deconstrctor" << endl;
		delete this;
	}
};

void VerifyObject(Base* input) {
	/*dynamic_cast检查两者是否有关系,即检查传入的是不是Derived对象,
	若是返回一个指针,若不是返回NULL*/
	if (dynamic_cast<Derived *> (input))  //向下转换,基类转派生类,安全的转换
		cout << "Is Derived" << endl;
	else
		cout << "Not Derived" << endl;
}

int main()
{
	Derived* isDerived = new Derived;
	Derived2* isDerived2 = new Derived2;
	NotDerived* notDetived = new NotDerived;
	
	cout << "---- static_cast ----" << endl;
	/*向上转换,可以使用static_cast,仅在编译阶段起作用,如下。*/
	Base* base = static_cast<Base*> (isDerived); //编译通过,类型相关,继承关系
	//Base* base = static_cast<Base*> (notDetived); //编译错误,类型不相关,不存在继承关系

	/*但是使用static_cast向下转换是不安全的转换,因为基类转成派生类对象,而派生类对象的某些方法可以没有实现,
	导致调用错误,但是由于存在继承关系使用static_cast进行向下转换可以编译通过的,但在运行阶段出问题。
	所以最好不要使用其进行向下转换
	*/

	cout << "---- dynamic_cast ----" << endl;
	VerifyObject(isDerived);
	VerifyObject(isDerived2);

	return 0;
}

output:

Base() constructor
Detived() constrctor
Base() constructor
Detived2() constrctor
NotDerived() constrctor
---- static_cast ----
---- dynamic_cast ----
Is Derived
Not Derived

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值