多态
2025/8/4大约 1 分钟
多态
如何实现多态?通过继承+虚函数
1.继承为什么不能实现多态?像Java那样?
不可以,测试代码如下:
定义父类
// 头文件
#pragma once
class 多态Father
{
public:
void play();
};
/// 实现代码
#include "多态Father.h"
#include <iostream>
void 多态Father::play()
{
std::cout << "father play..." << std::endl;
}
子类
#pragma once
#include "多态Father.h"
class 多态Son : public 多态Father
{
public:
void play();
};
// impl
#include "多态Son.h"
#include "iostream"
void 多态Son::play()
{
std::cout << "son play" << std::endl;
}
测试代码
#include <iostream>
#include <fstream>
#include <string>
#include "多态Father.h"
#include "多态Son.h"
void test(多态Father** men, int size) {
for (int i = 0; i < size; i++)
{
men[i]->play();
}
}
int main() {
多态Father f1;
多态Son s1, s2;
多态Father* fs[] = { &f1, &s1, &s2 };
test(fs, 3);
return 0;
}
输出
father play...
father play...
father play...
D:\code\cpp\ConsoleApplication1\Release\ConsoleApplication1.exe (进程 22492)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
可以看到,打印的都是父类的play函数
那么如何实现子类可以重写父类的play函数呢?
答案是将父类的函数,改造成虚函数
改造
修改父类头文件 将函数修改成虚函数
#pragma once
class 多态Father
{
public:
// 改成虚函数
virtual void play();
};
输出结果
father play...
son play
son play
D:\code\cpp\ConsoleApplication1\Release\ConsoleApplication1.exe (进程 19548)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
可以看到输出结果已经各是各的实现了。