C++类型转换

   C语言中,存在强制类型转换的概念。在C++中,C的作法一样适用。可是,C++也有本身的类型转换的方式,就是使用reinterpret_cast<>。例如,
安全

char* str = "chentong";
int* p = reinterpret_cast<int*>(str);

   经过这种方式,就把指向char*类型的str,强制转换成了指向int*。
ide

   仅仅这样作,是不够的。由于,str指向的一个字符串,一个肯定的字符串,也就是说,要求是不可改写,也就是可读不可写。因此,为了达到这一目的,咱们将str指向的内容不可修改。操做以下:
函数

const char* str = "chentong";

   这样作后,确实,str所指向的内容不可修改了,可是,这样作,又带来一个问题,那就是,reinterpre_cast<>这种强制转换,不能够去掉相似与const这样的属性。因此,咱们要经过一些手段,将str的const属性去掉。幸运的是,C++确实提供了解决方案。经过const_cast<>。代码以下:
this

const char* str = "chentong";
char* str2 = const_cast < char* > ( str );

   这样一来,就去掉了str的const属性。
spa

   那么,完整的操做方式,
指针

const char* str = "chentong";
char* str2 = const_cast < char* > ( str );
int* p = reinterpret_cast < char* > ( str2 );

   这样就完成了类型的转换。
对象

   接下来说一下动态类型转换。首先得清楚的是,动态类型转换,只能用于存在虚函数的类。假设我有三个类,
字符串

class Human {

public:
	 virtual void eating( void ) {

		cout << "use hand to eat" << endl;
	}
};

class Englishman : public Human {

public:
	//覆写
	void eating(void) {

		cout << "use knife to eat" << endl;
	}
};

class Chinese : public Human {

public:
	void eating(void) {

		cout << "use chopstick to eat" << endl;
	}
};

   而后我在global space中实现,对于不一样国家的人有不一样的吃饭方式这样一个函数。
it

void test_eating(Human& h) {

	h.eating();
}

   如今,我还想分辨这我的是英国人仍是中国人。那么,我该怎么作呢?ast

void test_eating(Human& h) {

	Englishman* pe = NULL;
	Chinese *pc = NULL;

	h.eating();
	
	if ( pe == dynamic_cast < Englishman* > ( &h ) );
	    cout << "this is Englishman" << endl;
	if ( pc == dynamic_cast < Chinese* > ( &h ) )
	    cout << "this is Chinese" << endl;
	
}

   在test_eating()函数中,我先定义两个变量,分别指向Englishman*和Chinese类型。那么,它是如何动态转换的呢?当一个类中有虚函数时,根据该类所建立的类对象中就会有一个指针,这个指针指向虚函数表,这个虚函数表中,含有类信息,根据这个类信息,就知道这个对象是属于哪一个类的。因此,这个类信息就能够肯定Human& h的h,是哪一个类的。

   最后,静态类型转换static_cast<>在进行上行转换时,是安全的。而在下行转换时,没有动态的检查,因此是不安全的,只有你编写代码时去检查是否符合逻辑。

相关文章
相关标签/搜索