一杯清酒邀明月
天下本无事,庸人扰之而烦耳。

实例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 }
posted on 2023-08-18 15:29  一杯清酒邀明月  阅读(39)  评论(0编辑  收藏  举报