您的位置:首页 > 编程语言 > C语言/C++

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

2016-02-29 18:05 507 查看
#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: