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

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

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dddd0216/article/details/79964778
个人分类: C++
所属专栏: C++基础
上一篇第三十八节 C++ 运算符重载 - 双目运算符
下一篇visual studio 使用技巧总结(含快捷键)
想对作者说点什么? 我来说一句

C++中的类型转换

2015年07月23日 44KB 下载

没有更多推荐了,返回首页

关闭
关闭