多态 (Polymorphism) 学习笔记

C++ 多态 - Polymorphism 学习笔记 1

代码例子:

Father.h

#include <iostream>
#include <string>

class Father
{
    public:
    void play();
};

Father.cpp

#include "Father.h"

void Father::play()
{
    cout<<"KTV singing"<<endl;
}

Son.h

#include <iostream>
#include <string>
#include "Father.h"

using namespace std;

class Son::public Father
{
  public: 
    void play();

};

Son.cpp

#include "Son.h"

void Son::play()
{
    cout<<"Play mobile game!"<<endl;
}

main.cpp

#include <iostream>
#include "Father.h"
#include "Son.h"
#include "string"

using namespace std;


void party(Father**men, int n)
{
    for(int i=0; i<n; i++)
    {
        men[i]->play();
    }
}


int main()
{
    Father father;
    Son son1, son2;
    Father* men[] = {&father, &son1, &son2};
    party(men, sizeof(men)/sizeof(men[0]);
    system("pause");
    return 0;
}

为什么输出结果都是KTV singing?

  • 因为都是使用的Father 类指针!那么怎么样才能解决呢?

    • 答:需要使用到多态!!!

也就是在代码中的 Father.h 里面的 play() 函数前加上virtual

#include <iostream>
#include <string>

class Father
{
    public:
    virtual void play();
};

加上后输出结果就会为

KTV singing
Play mobile game!
Play mobile game!

小总结:

多态的本质

形式上,使用统一的父亲类指针做一般性处理,但是实际上执行时,这个指针可能指向子类对象。

形式上,原本调用父亲类的方法,但是实际上会调用子类的同名方法。

虚函数如何定义?

在函数的返回类型之前使用Virtual

只有在成员函数的声明中添加Virtual, 成员函数的实现中不需要加上。

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值