多态与继承(上)

来源:互联网 发布:mac 抓取网页数据 编辑:程序博客网 时间:2024/05/02 00:16
函数重写:
在子类中定义与父类中原型相同的函数;
函数重写只发生在父类与子类之间;

class Parent//函数重写
{
public:
    void print()
    {
        cout<<"I'm Parent..."<<endl;
    }
};
class Child : public Parent
{
public:
    void print()
    {
        cout<<"I'm Child..."<<endl;
    }
};
父类中被重写的函数依然会继承给子类;
默认情况下子类中重写的函数将隐藏父类中的函数;
通过作用域分辨符::可以访问到父类中被隐藏的函数;

void run()
{
    Child child;
    Parent* pp = &child;
    Parent& rp = child;
    
    child.print();//编译器打印输出I,m child,实际正确
    
    pp->print();//编译器打印输出I,m parent,实际错误,应输出child
    
    rp.print();//编译器打印输出I,m parent。实际错误,应输出child
}


C++C相同,是静态编译型语言;
在编译时,编译器自动根据指针的类型判断指向的是一个什么样的对象;
所以编译器认为父类指针指向的是父类对象(根据赋值兼容性原则,这个假设合理);
由于程序没有运行,所以不可能知道父类指针指向的具体是父类对象还是子类对象;
从程序安全的角度,编译器假设父类指针只指向父类对象,因此编译的结果为调用父类的成员函数;


面向对象中的多态:



根据实际的对象类型决定函数调用语句的具体调用目标;

多态:同样的调用语句有多种不同的表现形态;


C++中通过virtual关键字对多态进行支持;

#include <cstdlib>
#include <iostream>
using namespace std;
class Boss//单例模式
{
private:
    static Boss* cInstance;
    
    Boss()
    {
    }
public:
    static Boss* GetInstance()
    {
        if( cInstance == NULL )
        {
             cInstance = new Boss();
        }
        
        return cInstance;
    }
    
    int fight()
    {
        cout<<"Boss::fight()"<<endl;
        return 10;
    }
};
Boss* Boss::cInstance = NULL;
class Master
{
public:
    virtual int eightSwordKill()
    {
        cout<<"Master::eightSwordKill()"<<endl;
        return 8;
    }
};
class NewMaster : public Master
{
public:
    virtual int eightSwordKill()//virtual关键字
    {
        cout<<"NewMaster::eightSwordKill()"<<endl;
        return Master::eightSwordKill() * 2;
    }
};
void fieldPK(Master* master, Boss* boss)
{
    int k = master->eightSwordKill();
    int b = boss->fight();
    
    if( k < b )
    {
        cout<<"Master is killed..."<<endl;
    }
    else
    {
        cout<<"Boss is killed..."<<endl;
    }
}
int main(int argc, char *argv[])
{
    Boss* boss = Boss::GetInstance();
    
    cout<<"Master vs Boss"<<endl;
    
    Master master;
    
    fieldPK(&master, boss);
    
    cout<<"New Master vs Boss"<<endl;
    
    NewMaster newMaster;
    
    fieldPK(&newMaster, boss);
    
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

函数重写是面向对象中很可能发生的情形
函数重写只可能发生在父类与子类之间
需要根据实际对象的类型确定调用的具体函数
virtual关键字是C++中支持多态的唯一方式
被重写的虚函数即可表现出多态的特性




0 0
原创粉丝点击