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

本文通过一个 C++ 示例介绍了静态绑定与动态绑定的区别,并演示了如何使用纯虚函数实现多态,以及如何进行类型转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如下:

#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
<<"发现二者不同! ";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值