c++基类与派生类之间的转换

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 class Box
 5 {
 6 public:
 7     void setWidth(double width){
 8         this->width=width;
 9     }
10     void setHieght(double height){
11         this->height=height;
12     }
13     void getWidth(){
14         cout<<width<<endl;
15     }
16 private:
17     double width,height;
18 };
19 class ColorBox : public Box{
20 public:
21     void setColor(string color){
22         this->color=color;
23         
24     }
25     void getColor(){
26         cout <<color<<endl;
27     }
28 
29 private:
30     string color;
31 };
32 int main(){
33     ColorBox colorbox;
34     Box  box;
35     colorbox.setColor("red");
36     colorbox.setHieght(10);
37     colorbox.setWidth(10);
38     colorbox.getColor();
39     colorbox.getWidth();
40     box=colorbox;
41     box.getWidth();
42     //使用指针
43     Box *ptr;
44     ptr=&colorbox;
45     cout<<ptr<<endl<<&box<<endl;
46     ptr->getWidth();
47     Box &r1=box;
48 
49     //r1和box共享同一段存储单元。也可以用子类对象初始化基类的引用变量
50     //r1和指针类型不同,box 和box*
51     r1.getWidth();
52     Box &r2=colorbox;
53     //派生类对象可以向基类对象的引用进行赋值或初始化
54     //但是不能调用子类的数据成员,此时基类引用并不是派生类对象的别名,也不与派生类共享同一段存储单元。
55     //它只是派生类中基类部分的别名,基类引用与派生类中基类部分共享同一段存储单元。0027F868
56     //0027F850
57     r2.getWidth();
58     cout<<&r2<<endl<<&box<<endl;
59 
60     return 0;
61 }

基类与派生类之间的转换,如果基类的对象想要访问子类的数据成员函数就要,去向下转型。

原文地址:https://www.cnblogs.com/zhangyanguang/p/4907431.html