C ++ノート5型変換


次のコードの開始コード

#include <iostream>

using namespace std;

C ++型変換

  • static_castの一般的な状況
  • const_castを定数に
  • dynamic_castサブクラスタイプは親タイプに変換されます
  • reinterpret_cast関数ポインタ変換、移植性なし

元の型変換、すべてのケースはある方法で書かれています、読みやすさは高くありません、潜在的なリスクがあるかもしれません

static_cast

void* func(int type){	
	switch (type){
	case 1:	{
				int i = 9;
				return &i;
	}
	case 2:	{
				int a = 'X';
				return &a;
	}
	default:{
				return NULL;
	}

	}	
}

void func2(char* c_p){
	cout << *c_p << endl;
}

void main(){	
	//int i = 0;
	//自动转换
	//double d = i;
	//double d = 9.5;
	//int i = d;

	//int i = 8;
	//double d = 9.5;
	//i = static_cast<int>(d);
	
	//void* -> char*
	//char* c_p = (char*)func(2);
	//char* c_p = static_cast<char*>(func(2));

	//C++ 意图明显
	func2(static_cast<char*>(func(2)));
	//C
	func2((char*)(func(2)));
	
	system("pause");
}

const_castを定数に

void func(const char c[]){
	//c[1] = 'a';
	//通过指针间接赋值
	//其他人并不知道,这次转型是为了去常量
	//char* c_p = (char*)c;
	//c_p[1] = 'X';
	//提高了可读性
	char* c_p = const_cast<char*>(c);
	c_p[1] = 'Y';

	cout << c << endl;
}

void main(){
	char c[] = "hello";
	func(c);

	system("pause");
}

dynamic_castサブクラスタイプは親タイプに変換されます

class Person{
public:
	virtual void print(){
		cout << "人" << endl;
	}
};

class Man : public Person{
public:
	void print(){
		cout << "男人" << endl;
	}

	void chasing(){
		cout << "泡妞" << endl;
	}
};


class Woman : public Person{
public:
	void print(){
		cout << "女人" << endl;
	}

	void carebaby(){
		cout << "生孩子" << endl;
	}
};

void func(Person* obj){	

	//调用子类的特有的函数,转为实际类型
	//并不知道转型失败
	//Man* m = (Man*)obj;
	//m->print();

	//转型失败,返回NULL
	Man* m = dynamic_cast<Man*>(obj);	
	if (m != NULL){
		m->chasing();
	}

	Woman* w = dynamic_cast<Woman*>(obj);
	if (w != NULL){
		w->carebaby();
	}
}

void main(){
	
	//Woman w1;
	//Person *p1 = &w1;

	//func(p1);

	Woman w1;
	Woman* w_p = &w1;
	

	system("pause");
}

reinterpret_cast関数ポインタ変換、移植性なし

移植性がない:一部のコンパイラはそれをサポートしていない可能性があります。
reinterpret_castの最も一般的な使用法は、「関数ポインター」タイプを変換することです。特定のタイプの関数ポインタを格納する配列があるとします。

void func1(){
	cout << "func1" << endl;
}

char* func2(){
	cout << "func2" << endl;
	return "abc";
}

typedef void(*f_p)();

void main(){
	//函数指针数组
	f_p f_array[6];
	//赋值
	f_array[0] = func1;

	//C方式
	//f_array[1] = (f_p)(func2);
	//C++方式
	f_array[1] = reinterpret_cast<f_p>(func2);

	f_array[1]();

	system("pause");
}

typedef void(* FuncPtr)(); // FuncPtrは関数を指すポインターであり、この関数はvoid(関数ポインター)を返します

おすすめ

転載: blog.csdn.net/fxjzzyo/article/details/84400804