当前位置: 代码迷 >> 综合 >> 多态(Polymorphism)和对象切割(Object Slicing)的小例子
  详细解决方案

多态(Polymorphism)和对象切割(Object Slicing)的小例子

热度:35   发布时间:2023-12-10 01:45:04.0

如下:

#include  < iostream >
using   namespace  std;
class  Grandfather {
public:
    
virtual void display()=0;
    
void run(){                    
        cout
<<"Grandfather Run!!! ";
    }

}
;
class  Father: public  Grandfather {
public:
    
int fatherValue;
    
void display(){
        cout
<<"Father Display!! ";
    }

    
void run(){
        cout
<<"Father Run!!! ";
    }

}
;
class  Uncle: public  Grandfather {
public:
    
int uncleValue;
    
void display(){
        cout
<<"Uncle Display!! ";
    }

    
void run(){
        cout
<<"Uncle Run!!! ";
    }

}
;
class  Son: public  Father {
public:
    
int sonValue;
    
void display(){
        cout
<<"Son Display!! ";
    }

}
;
void  main() {
    Grandfather
* grandfather_pt=NULL;
    Father
* father_pt=NULL;
    Son
* son_pt=NULL;

    Father father;
    Uncle uncle;
    Son son;

    cout
<<"静态绑定 不用virtual关键字: ";
    grandfather_pt
=&uncle;
    grandfather_pt
->run();
    grandfather_pt
=&father;
    grandfather_pt
->run();

    cout
<<" 动态绑定 纯虚函数: ";
    grandfather_pt
=&uncle;
    grandfather_pt
->display();
    grandfather_pt
=&father;
    grandfather_pt
->display();

    cout
<<" 指针强制转换 ";
    ( (Father
*)(&son) )->display();
//    ( (Father*)(&son) )->run();

    cout
<<" 对象强制转换 ";
    ((Father)son).display();        
//只允许upcasting,不允许downcasting
    cout<<" 编译器为了防止对象切割的发生,自动调用拷贝构造函数,因此,比较地址: ";
    cout
<<( father_pt=&((Father)son) )<<endl;    //注意优先级
    cout<<&son<<endl;
    cout
<<"发现二者不同! ";
}
  相关解决方案