在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 <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;
}
// 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()時,會根據實際對象類型(Circle或Rectangle)調用相應的draw()方法,實現運行時多態。