C++ 接口(抽象类)
讲解 C++ 如何借助含纯虚函数的抽象基类(ABC)定义标准化接口、抽象类与具体类的实例化边界、Shape 面积多态示例以及面向接口扩展的架构策略。
学完这一章,你能够
- 讲解 C++ 如何借助含纯虚函数的抽象基类(ABC)定义标准化接口、抽象类与具体类的实例化边界、Shape 面积多态示例以及面向接口扩展的架构策略。
纯虚函数与抽象基类(ABC)接口契约
接口用于描述类型应当具备的外部行为契约而不绑定具体实现。C++ 没有独立的 `interface` 关键字,而是以抽象类(Abstract Base Class,简称 ABC)充当接口——只要类中至少存在一个以 `= 0` 声明的纯虚函数(例如 `virtual double getVolume() = 0;`),该类即成为抽象类。需注意抽象类属于语言级接口机制,不应与“接口实现分离”的数据抽象概念混为一谈。
抽象类不能直接创建对象(试图实例化会触发编译错误),只能被继承或通过基类指针/引用操作。只有重写了继承自抽象基类的全部纯虚函数的派生类才能成为具体类(Concrete Class)并被实例化;若漏掉任意纯虚函数,派生类仍保持抽象状态。
抽象类实战示例与系统扩展策略
在几何图形接口示例中,抽象基类 `Shape` 声明纯虚接口 `virtual int getArea() = 0;` 并提供公共的宽高设置方法,具体派生类 `Rectangle` 与 `Triangle` 分别以 `width * height`(5×7=35)和 `(width * height) / 2`(整数除法得 17)实现同一接口;作为多态基类时还应补充 `virtual ~Shape() = default;` 以确保安全释放。
面向对象系统常以抽象基类向外部模块或插件定义统一标准协议:所有对外能力以公有纯虚函数形式固定在基类中,各具体模块分别继承实现。如此一来,即便在核心框架上线之后,新增实现类也能平滑接入现有多态容器与调度流程而无需改动调用侧代码。
验证 ABC 抽象类型特征、Rectangle/Triangle 具体实现、多态扩展与部分实现抽象性
展开查看收起
#include <iostream>
#include <memory>
#include <string>
#include <type_traits>
#include <vector>
class Shape {
public:
virtual int getArea() const = 0;
virtual ~Shape() = default;
void setWidth(int w) { width = w; }
void setHeight(int h) { height = h; }
protected:
int width = 0;
int height = 0;
};
class Rectangle : public Shape {
public:
int getArea() const override { return width * height; }
};
class Triangle : public Shape {
public:
int getArea() const override { return (width * height) / 2; }
};
class Square : public Shape {
public:
explicit Square(int side) { setWidth(side); setHeight(side); }
int getArea() const override { return width * height; }
};
class PluginInterface {
public:
virtual std::string name() const = 0;
virtual int run(int x) const = 0;
virtual ~PluginInterface() = default;
};
class PartialPlugin : public PluginInterface {
public:
std::string name() const override { return "partial"; }
// run() intentionally left pure virtual -> still abstract
};
class CompletePlugin : public PartialPlugin {
public:
int run(int x) const override { return x * 3; }
};
int main() {
// 1. Abstract class trait check (ABC cannot be instantiated; concrete subclasses can)
static_assert(std::is_abstract_v<Shape>, "Shape must be abstract");
static_assert(!std::is_abstract_v<Rectangle>, "Rectangle must be concrete");
static_assert(!std::is_abstract_v<Triangle>, "Triangle must be concrete");
bool ok1 = std::is_abstract_v<Shape> && !std::is_abstract_v<Rectangle> && !std::is_abstract_v<Triangle>;
// 2. Rectangle and Triangle implementing Shape::getArea()
Rectangle rect;
rect.setWidth(5);
rect.setHeight(7);
Triangle tri;
tri.setWidth(5);
tri.setHeight(7);
std::string act2 = "rect=" + std::to_string(rect.getArea()) + ",tri=" + std::to_string(tri.getArea());
const std::string exp2 = "rect=35,tri=17";
bool ok2 = (act2 == exp2);
// 3. Extensible polymorphic interface container
std::vector<std::unique_ptr<Shape>> shapes;
auto r = std::make_unique<Rectangle>();
r->setWidth(5); r->setHeight(7);
auto t = std::make_unique<Triangle>();
t->setWidth(5); t->setHeight(7);
shapes.push_back(std::move(r));
shapes.push_back(std::move(t));
shapes.push_back(std::make_unique<Square>(4));
int total_area = 0;
for (const auto& sp : shapes) {
total_area += sp->getArea();
}
bool ok3 = (total_area == 68);
// 4. Partially implemented subclass stays abstract; full implementation is concrete
static_assert(std::is_abstract_v<PartialPlugin>, "PartialPlugin must remain abstract");
static_assert(!std::is_abstract_v<CompletePlugin>, "CompletePlugin must be concrete");
CompletePlugin cp;
PluginInterface& iface = cp;
std::string act4 = iface.name() + ":" + std::to_string(iface.run(7)) +
":partial_abs=" + (std::is_abstract_v<PartialPlugin> ? "1" : "0");
const std::string exp4 = "partial:21:partial_abs=1";
bool ok4 = (act4 == exp4);
std::cout << "{\n"
<< " \"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\",\n"
<< " \"cases\": [\n"
<< " {\"name\": \"abc_type_traits_purity\", \"expected\": true, \"actual\": "
<< (ok1 ? "true" : "false") << ", \"passed\": " << (ok1 ? "true" : "false") << "},\n"
<< " {\"name\": \"concrete_shape_implementations\", \"expected\": \"" << exp2
<< "\", \"actual\": \"" << act2 << "\", \"passed\": " << (ok2 ? "true" : "false") << "},\n"
<< " {\"name\": \"polymorphic_interface_extensibility\", \"expected\": 68, \"actual\": "
<< total_area << ", \"passed\": " << (ok3 ? "true" : "false") << "},\n"
<< " {\"name\": \"partial_vs_complete_override\", \"expected\": \"" << exp4
<< "\", \"actual\": \"" << act4 << "\", \"passed\": " << (ok4 ? "true" : "false") << "}\n"
<< " ]\n"
<< "}\n";
return 0;
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
会引发编译错误。只要类中仍有尚未被非纯重写的纯虚函数,该派生类本身就依然是抽象类,不能直接实例化。