注册 登录
编程论坛 C++教室

一定要使用指针吗?

maiiho 发布于 2008-10-25 22:14, 631 次点击
#include<iostream.h>
class Grandam {
    public:
      virtual void introduce_self()  // 定义虚函数introduce_self()
      { cout<<"I am grandam."<<endl; }
    };
class Mother:public Grandam {
    public:
        void introduce_self()     // 重新定义虚函数introduce_self()
        { cout<<"I am mother."<<endl;}
};
class Daughter:public Mother {
    public:
        void introduce_self()     // 重新定义虚函数introduce_self()
        { cout<<"I am daughter."<<endl;}
};
void main()
{
    Grandam *ptr;
    Grandam g;
    Mother m;
Daughter d;
     ptr=&g;
     ptr->introduce_self(); //调用基类Grandam的introduce_self()
     ptr=&m;
     ptr->introduce_self(); // 调用派生类Mother的introduce_self()
     ptr=&d;
     ptr->introduce_self();    //调用派生类

                                               //  Daughter的introduce_self()
}
5 回复
#2
maiiho2008-10-25 22:17
虽然使用对象名和点运算符的方式也可以调用虚函数,但只有
通过基类指针访问虚函数才能获得运行是的多态。

答案我找到了.
#3
maiiho2008-10-25 22:18
以上所述的多态的意思,是在程序运行的时候?
#4
newyj2008-10-25 23:01
定义基类引用 也可以实现 多态
#5
maiiho2008-10-26 00:06
多态是什么意思?
不是一条指令多个行为的意思么?
#6
leeco2008-10-26 15:43
回复 5# maiiho 的帖子
多态就是晚绑定、动态绑定。
1