C++多态与指针的强制转换

#include "stdafx.h"
#include <iostream>
using namespace std;


class Base  
{  
public:  
virtual void f(float x)
{
cout << "Base::f(float) " << x << endl;
}  
void g(float x)
{
cout << "Base::g(float) " << x << endl;
}  
void h(float x)
{
cout << "Base::h(float) " << x << endl;
}  
};  
class Derived : public Base  
{  
public:  
virtual void f(float x)
{
cout << "Derived::f(float) " << x << endl;
}  
void g(int x)
{
cout << "Derived::g(int) " << x << endl;
}  
void h(float x)
{
cout << "Derived::h(float) " << x << endl;
}  
};


int _tmain(int argc, _TCHAR* argv[])
{
Derived d;  
Base *pb = &d;  
Derived *pd = &d;  
// Good : behavior depends solely on type of the object  
pb->f(3.14f); // Derived::f(float) 3.14  
pd->f(3.14f); // Derived::f(float) 3.14  
// Bad : behavior depends on type of the pointer  
pb->g(3.14f); // Base::g(float) 3.14  
pd->g(3.14f); // Derived::g(int) 3 (surprise!)  
// Bad : behavior depends on type of the pointer  
pb->h(3.14f); // Base::h(float) 3.14 (surprise!)  
pd->h(3.14f); // Derived::h(float) 3.14  


cout<<endl<<endl;


Base *pnb = new Derived;
Derived *pnd = new Derived;


pnb->f(6.28f);// Derived::f(float) 6.28
pnd->f(6.28f);// Derived::f(float) 6.28


pnb->g(6.28f);//Base::g(float) 6.28
pnd->g(6.28f);// Derived::g(int) 6


pnb->h(6.28f);//Base::h(float) 6.28
pnd->h(6.28f);// Derived::h(float) 6.28


cout<<endl<<endl;


Base *b = new Base;
Derived *pzd = (Derived*)b;


b->f(9.42f);//Base::f(float) 9.42
pzd->f(9.42f);//Base::f(float) 9.42


b->g(9.42f);//Base::g(float) 9.42
pzd->g(9.42f);Derived::g(int) 9


b->h(9.42f);//Base::h(float) 9.42
pzd->h(9.42f);Derived::h(float) 9.42




system("pause");
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值