理解object slicing

#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<<"发现二者不同! ";
}

 输出为:

静态绑定 不用virtual关键字:

Grandfather Run!!!

Grandfather Run!!!

 动态绑定 纯虚函数:

Uncle Display!!

Father Display!!

 指针强制转换

Son Display!!

 对象强制转换 Father Display!!

 编译器为了防止对象切割的发生,自动调用拷贝构造函数,因此,比较地址:

//0012FDB8

//0012FE88

发现二者不同!

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/SearchLife/archive/2009/03/12/3985139.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值