C++ Type Conversion
-
static_cast Universal
-
const_cast de-constant
-
dynamic_cast subclass type to parent type (converting an object to its actual type is unsuccessful to NULL)
-
The pointer transformation of reinterpret_cast function does not have portability
-
Primitive type conversion, all of which are written in a way that is not readable and potentially risky
- static_cast Universal
void* func(int type) { switch (type) { case 1: { int i = 9; return &i; } case 2: { int a = 'X'; return &a; } } return NULL; } void func2(char* c_p) { cout << *c_p << endl; } void main() { int i = 10; //Automatic conversion double d = i; cout << "i=:"<< i << endl;//10 cout << "d=:" << d << endl;//10 double m = 9.5; int n = m; cout << "m=:" << m << endl;//9.5 cout << "n=:" << n << endl;//9 double x = 9.5; int y = 8; y = static_cast<int>(x); cout << "y=:" << y << endl;//9 //Type Conversion of C Language //char* c_p = (char*)func(2); //C++ Type Conversion char* c_p = static_cast<char*>(func(1)); //C++ has obvious intentions func2(static_cast<char*>(func(1))); //C func2((char*)(func(2))); getchar(); }
- const_cast de-constant
void func(const char c[]) { //C[1]='a'; //Can not be modified //Indirect assignment by pointer //Others don't know that this transition is to go constant. //char* c_p = (char*)c; //c_p[1] = 'X'; //Enhanced readability char* c_p = const_cast<char*>(c);//Use const_cast to remove const restriction c_p[1] = 'Y'; cout << c << endl; } void main() { char c[] = "hello"; func(c); system("pause"); }
- dynamic_cast subclass type to parent type (converting an object to its actual type is unsuccessful to NULL)
class Person { public: virtual void print() { cout << "Parent class" << endl; } }; class Man : public Person { public: void print() { cout << "male" << endl; } void chasing() { cout << "Then na na." << endl; } }; class Woman : public Person { public: void print() { cout << "female" << endl; } void carebaby() { cout << "Aha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha" << endl; } }; void func(Person* obj) { //Call the specific function of the subclass to the actual type //Do not know the failure of transformation //Man* m = (Man*)obj; //m->print(); //Transition Failure, Return to 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); system("pause"); }
- The pointer transformation of reinterpret_cast function does not have portability
void func1() { cout << "func1" << endl; } char* func2() { cout << "func2" << endl; return const_cast<char*>("abc"); } typedef void(*f_p)(); void main() { //Function pointer array f_p f_array[6]; //assignment f_array[0] = func1; //C mode //f_array[1] = (f_p)(func2); //C++ mode f_array[1] = reinterpret_cast<f_p>(func2); f_array[1](); system("pause"); }