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

来源:互联网 发布:高校状态数据采集平台 编辑:程序博客网 时间:2024/05/22 17:15
#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