如下:
#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<<"发现二者不同! ";
}
本文通过一个 C++ 示例介绍了静态绑定与动态绑定的区别,并演示了如何使用纯虚函数实现多态,以及如何进行类型转换。
155

被折叠的 条评论
为什么被折叠?



