c++函数模板和类模板——DAY8

 

 

 

 

 

C语言的强制类型转换(Type Cast)很简单,不管什么类型的转换统统是:

TYPE b = (TYPE)a   

C++的类型转换有如下四种:

    1.static_cast                静态类型转换。如int转换成char。编译的时c++编译器会做类型检查;基本类型能转换 但是不能转换指针类型

 

 

               2.reinterpreter_cast     重新解释类型

          3.dynamic_cast          命名上理解是动态类型转换。如子类和父类之间的多态类型转换。

               4.const_cast,            字面上理解就是去const属性。

4种类型转换的格式:

         TYPE B = static_cast<TYPE> (a)  

注:

C语言中不能隐式类型转换的,在c++中可以用 reinterpret_cast<>() 进行强行类型 解释

如以下示例:

#include<iostream>
using namespace std;
void main()
{
	double dpi = 3.1415;
	int number = (int)dpi;//
	int number2 = static_cast<int>(dpi);//静态类型转换,编译时c++编译器会做类型检查,如果不通过会报错
	//c语言中隐式类型转换的地方均可以进行类型转换,
	//char *转int *不行
	char *p1 = (char *)"hello...itcast";
	int *p2 = NULL;
	p2 = reinterpret_cast<int *>(p1);
	cout << "p1:" << p1 << endl;
	cout << "p2" << (p2) << endl;

	cout << "hello"<< endl;
}

 

3.dynamic_cast:主要用于类层次结构中父类和子类之间指针和引用的转换,由于具有运行时类型检查,因此可以保证下行转换的安全性,转换成功就返回转换后的正确类型指针,如果转换失败,则返回NULL。在转换时,dynamic_cast会检查转换的source对象是否真的可以转换成target类型。

 

#include <iostream>
using namespace std;

class Tree {};

class Animal
{
public:
	virtual void cry() = 0;//用虚函数的原因:指向基类的指针在操作它的多态类对象时,会根据不同的类对象,调用其相应的函数。
};

class Dog : public Animal
{
public:
	virtual void cry()
	{
		cout << "汪汪" << endl;
	}
	void doHome()
	{
		cout << "看家" << endl;
	}
};

class Cat : public Animal
{
public:
	virtual void cry()
	{
		cout << "喵喵" << endl;
	}
	void doThing()
	{
		cout << "抓老鼠" << endl;
	}
};

void playObj(Animal *base)
{
	base->cry(); // 1有继承 2虚函数重写 3 父类指针 指向子类对象  ==>多态
	//能识别子类对象
	// dynamic_cast 运行时类型识别  RIIT

	Dog *pDog = dynamic_cast<Dog *>(base);
	if (pDog != NULL)
	{
		pDog->doHome(); 	}

	Cat *pCat = dynamic_cast<Cat *>(base);	//父类对象 ===> 子类对象 
											//向下转型  
											//把老子 转成 小子 
	if (pCat != NULL)
	{
		pCat->doThing();  //让够 做自己 特有的工作 
	}
}

void main()
{
	Dog d1;
	Cat c1;

	Animal *pBase = NULL;

	pBase = &d1;

	pBase = static_cast<Animal *>(&d1); //让C++编译在编译的时候进行 类型检查 

	//强制类型转换 
	pBase = reinterpret_cast<Animal *>(&d1);

	{
		Tree t1;
		//pBase = static_cast<Animal *>(&t1); // C++编译器会做类型检查
		pBase = reinterpret_cast<Animal *>(&t1);  //reinterpret_cast 重新解释 ....强制类转换的味道
	}
	//

	playObj(&d1);
	playObj(&c1);

	system("pause");
}

 

 

 

 

 

猜你喜欢

转载自blog.csdn.net/qq_41536360/article/details/89408900