C++多态基础

来源:互联网 发布:js input 禁止光标 编辑:程序博客网 时间:2024/06/05 17:11
#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
/*
多态:
    派生类的指针可以赋给基类指针 base* = child;
    通过基类指针调用基类和派生类中的同名虚函数时,
    若该指针指向一个基类对象,那么被调用的是基类的虚函数
    若该指针指向一个派生类的对象 那么调用的是派生类的虚函数
    
*/
class Parent {
    public:
        virtual void print();
};
class Child:public Parent{
    public:
        virtual void print();
};
int main(int argc, char** argv) {
    Child c;
    Parent *p = & c;//派生类的指针赋给 基类类的指针
    p->print();//调用那个虚函数取决与 p的指针指向那一个对象.
    return 0;
}

/*
多态的形式二:
派生类的对象赋给基类的引用
通过基类的引用调用基类和派生类中的同名虚函数时,
1.若该引用是一个基类对象,那么调用基类的虚函数
2.若该引用引用的是一个派生类的对象,那么被调用的是派生类的虚函数
这种机制叫做多态.
Child c;
Parent &p = c; 派生类的对象赋给基类的引用
p.print//调用那个虚函数取决与p引用哪种类的对象。

*/


多态的作用增加程序的可扩充性

0 0
原创粉丝点击