答案是使用抽象基类和多态实现统一接口调用不同子类方法。定义含纯虚函数的Shape类,派生Circle、Rectangle类并重写area()和draw(),通过基类指针调用实际对象函数,实现运行时多态。

在C++中实现抽象接口并调用多种子类对象,核心是使用抽象基类(纯虚类)和多态机制。通过定义统一接口,让不同子类提供各自实现,运行时通过基类指针或引用调用实际对象的方法。
创建一个包含纯虚函数的基类,作为所有子类的公共接口。这个类不能被实例化,只用于派生具体类。
class Shape {
public:
virtual ~Shape() = default; // 虚析构函数
virtual double area() const = 0; // 纯虚函数
virtual void draw() const = 0; // 纯虚函数
};
注意:析构函数设为虚函数,防止删除派生类对象时出现未定义行为。
从抽象类派生具体类,并实现各自的虚函数逻辑。
立即学习“C++免费学习笔记(深入)”;
class Circle : public Shape {
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return 3.14159 * radius * radius;
}
void draw() const override {
std::cout << "Drawing a circle\n";
}
};
<p>class Rectangle : public Shape {
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override {
return width * height;
}
void draw() const override {
std::cout << "Drawing a rectangle\n";
}
};</p>使用基类指针或引用存储子类对象,通过多态调用对应方法。
#include <vector>
#include <memory>
<p>int main() {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(5.0));
shapes.push_back(std::make_unique<Rectangle>(4.0, 6.0));</p><pre class='brush:php;toolbar:false;'>for (const auto& shape : shapes) {
std::cout << "Area: " << shape->area() << "\n";
shape->draw();
}
return 0;}
输出结果:
Area: 78.5398 Drawing a circle Area: 24 Drawing a rectangle
通过虚函数表(vtable),程序在运行时动态绑定到实际对象的实现。只要接口一致,新增子类无需修改调用代码。
基本上就这些。只要掌握抽象基类 + 虚函数 + 基类指针,就能灵活管理多种类型对象。
以上就是C++如何实现抽象接口调用多种子类对象的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号