温馨提示×

Linux C++中如何使用多态特性

小樊
60
2025-04-20 04:40:33
栏目: 编程语言

在C++中,多态是通过虚函数实现的。虚函数允许子类重写基类中的方法,从而实现运行时多态。以下是一个简单的示例,展示了如何在Linux环境下使用C++实现多态:

  1. 首先,创建一个基类Shape,并声明一个虚函数draw()
// Shape.h #ifndef SHAPE_H #define SHAPE_H class Shape { public: virtual void draw() const = 0; // 纯虚函数,使Shape成为抽象类 virtual ~Shape() {} // 虚析构函数,确保正确释放子类资源 }; #endif // SHAPE_H 
  1. 创建两个子类CircleRectangle,分别继承自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 
  1. 实现CircleRectangle类的draw()方法:
// Circle.cpp #include "Circle.h" #include <iostream> void Circle::draw() const { std::cout << "Drawing a circle" << std::endl; } 
// Rectangle.cpp #include "Rectangle.h" #include <iostream> void Rectangle::draw() const { std::cout << "Drawing a rectangle" << std::endl; } 
  1. 在主函数中使用多态特性:
// main.cpp #include <iostream> #include <memory> #include "Circle.h" #include "Rectangle.h" int main() { std::unique_ptr<Shape> shape1 = std::make_unique<Circle>(); std::unique_ptr<Shape> shape2 = std::make_unique<Rectangle>(); shape1->draw(); // 输出 "Drawing a circle" shape2->draw(); // 输出 "Drawing a rectangle" return 0; } 

在这个示例中,我们使用了C++11的std::unique_ptr智能指针来管理对象的生命周期。当调用shape1->draw()shape2->draw()时,会根据实际对象类型(CircleRectangle)调用相应的draw()方法,实现运行时多态。

0