利用案例简要阐述C++的强制类型转换
C语言的风格: type b = (type) a;
C++语言风格:type b = 转换形式 <type> (a);
四种形式的介绍:
- static_cast 静态类型转化(让C++编译器在编译时进行类型检查)
- reinterpreter_cast重新解释类型
- dynamic_cast命名上理解是动态类型转换,如子类和父类之间的多态类型转换
- const_cast 字面上理解就是去const属性
案例一:主要进行解释dynamic_cast
#include <iostream> using namespace std; class Animal { public: virtual void cry() = 0; }; class Dog:public Animal { public: virtual void cry() { cout << "wang wang" << endl; } void doHome() { cout << "watch door" << endl; } }; class Cat:public Animal { public: virtual void cry() { cout << "miao miao" << endl; } void catchMouse() { cout << "catch mouse" << endl; } }; void playObj(Animal* base) { base->cry(); Dog* d; d = dynamic_cast<Dog*>(base); if (d != NULL) { d->doHome(); } Cat* c; c = dynamic_cast<Cat*>(base); if (c != NULL) { c->catchMouse(); } } int main() { Dog d; Cat c; /* playObj(&d); playObj(&c); */ Animal* a; a = static_cast<Animal*>(&d); a->cry(); return 0; }
案例二:主要解释const_cast
#include <iostream> using namespace std; void stringPlay(const char *p) { char* pBuf; pBuf = const_cast<char *>(p); pBuf[0] = 'Z'; } int main() { char p[] = "abcdefghijk"; //已经分配空间 stringPlay(p); cout << p << endl; const char *newP = "abcdefgh"; /* newP这是指向一个字符串常量,所以char *newP = "abcdefgh";会出现语法错误, 没有给newP分配空间,所以不能调用上面的方法 */ return 0; }
详细解释可以参考:https://www.cnblogs.com/Allen-rg/p/6999360.html