实例1:静态强制转换
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 class Company 6 { 7 public: 8 Company(string theName,string product); 9 virtual void printInfo(); 10 11 protected: 12 string name; 13 string product; 14 }; 15 Company::Company(string theName,string product) 16 { 17 name = theName; 18 this->product = product; 19 } 20 void Company::printInfo() 21 { 22 cout << "这个公司的名字叫:" << name << "正在生产" << product << "\n"; 23 } 24 25 class TechCompany:public Company 26 { 27 public: 28 TechCompany(string theName,string product); 29 virtual void printInfo(); 30 }; 31 TechCompany::TechCompany(string theName,string product):Company(theName,product) 32 { 33 } 34 void TechCompany::printInfo() 35 { 36 cout << name << "公司大量生产了 " << product << "这款产品!\n"; 37 } 38 39 int main() 40 { 41 Company *company = new TechCompany("APPLE","Iphone");//定义TechCompany对象,Company类型 42 //指针company指向其地址 43 TechCompany *techCompany = (TechCompany*)company; //将Company类型强制转换为TechCompany类型 44 45 techCompany->printInfo(); 46 47 delete company;//释放内存(此处company与techCompany两个指针都指向TechCompany定义的对象) 48 //所以释放内存只需要释放一次即可 49 company = NULL; 50 techCompany = NULL; 51 52 return 0; 53 }
实例2:动态强制转换
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 class Company 6 { 7 public: 8 Company(string theName,string product); 9 virtual void printInfo(); 10 11 protected: 12 string name; 13 string product; 14 }; 15 Company::Company(string theName,string product) 16 { 17 name = theName; 18 this->product = product; 19 } 20 void Company::printInfo() 21 { 22 cout << "这个公司的名字叫:" << name << "正在生产" << product << "\n"; 23 } 24 25 class TechCompany:public Company 26 { 27 public: 28 TechCompany(string theName,string product); 29 virtual void printInfo(); 30 }; 31 TechCompany::TechCompany(string theName,string product):Company(theName,product) 32 { 33 } 34 void TechCompany::printInfo() 35 { 36 cout << name << "公司大量生产了 " << product << "这款产品!\n"; 37 } 38 39 int main() 40 { 41 Company *company = new Company("APPLE","Iphone");//定义Company对象, 42 //指针company类型为Company,指向其地址 43 TechCompany *techCompany = dynamic_cast<TechCompany*>(company); //将Company类型强制转换为TechCompany类型 44 45 if(techCompany != NULL) 46 { 47 cout << "成功!\n"; 48 } 49 else 50 { 51 cout << "悲催!\n"; 52 } 53 delete company;//释放内存(此处company与techCompany两个指针都指向TechCompany定义的对象) 54 //所以释放内存只需要释放一次即可 55 company = NULL; 56 techCompany = NULL; 57 58 return 0; 59 }标签:类型转换,product,string,printInfo,Company,C++,第三十七,theName,include From: https://www.cnblogs.com/ybqjymy/p/17640647.html