阅读量:0
在C++中,多态是通过虚函数实现的。虚函数允许子类重写基类中的方法,从而实现运行时多态。以下是一个简单的示例,展示了如何在Linux环境下使用C++实现多态:
- 首先,创建一个基类
Shape,并声明一个虚函数draw():
// Shape.h
#ifndef SHAPE_H
#define SHAPE_H
class Shape {
public:
virtual void draw() const = 0; // 纯虚函数,使Shape成为抽象类
virtual ~Shape() {} // 虚析构函数,确保正确释放子类资源
};
#endif // SHAPE_H
- 创建两个子类
Circle和Rectangle,分别继承自Shape类,并重写draw()方法:
// Circle.h
#ifndef CIRCLE_H
#define CIRCLE_H
#include "Shape.h"
class Circle : public Shape {
public:
void draw() const override; // 重写基类的虚函数
};
#endif // CIRCLE_H
// Rectangle.h
#ifndef RECTANGLE_H
#define RECTANGLE_H
#include "Shape.h"
class Rectangle : public Shape {
public:
void draw() const override; // 重写基类的虚函数
};
#endif // RECTANGLE_H
- 实现
Circle和Rectangle类的draw()方法:
// Circle.cpp
#include "Circle.h"
#include
void Circle::draw() const {
std::cout << "Drawing a circle" << std::endl;
}
// Rectangle.cpp
#include "Rectangle.h"
#include
void Rectangle::draw() const {
std::cout << "Drawing a rectangle" << std::endl;
}
- 在主函数中使用多态特性:
// main.cpp
#include
#include
#include "Circle.h"
#include "Rectangle.h"
int main() {
std::unique_ptr shape1 = std::make_unique();
std::unique_ptr shape2 = std::make_unique();
shape1->draw(); // 输出 "Drawing a circle"
shape2->draw(); // 输出 "Drawing a rectangle"
return 0;
}
在这个示例中,我们使用了C++11的std::unique_ptr智能指针来管理对象的生命周期。当调用shape1->draw()和shape2->draw()时,会根据实际对象类型(Circle或Rectangle)调用相应的draw()方法,实现运行时多态。
以上就是关于“Linux C++中如何使用多态特性”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm