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, 成员函数的实现中不需要加上。