首页 > 应用开发 > IT综合 > C++继承与多态解析:代码复用与扩展的核心机制
# C++继承与多态解析:代码复用与扩展的核心机制
## 继承机制的基础原理
C++继承是面向对象编程的核心特性,允许从已有类派生新类,实现代码重用和层次结构组织。理解继承的访问控制和构造顺序是构建健壮类体系的基础。
```cpp
// 基础继承示例
class Animal {
protected:
std::string name;
int age;
public:
Animal(const std::string& name, int age) : name(name), age(age) {
std::cout << "Animal构造函数: " << name << std::endl;
}
virtual ~Animal() {
std::cout << "Animal析构函数: " << name << std::endl;
}
virtual void makeSound() const {
std::cout << name << " 发出声音" << std::endl;
}
void sleep() const {
std::cout << name << " 正在睡觉" << std::endl;
}
const std::string& getName() const { return name; }
int getAge() const { return age; }
};
// 公有继承:保持基类访问权限
class Dog : public Animal {
private:
std::string breed;
public:
Dog(const std::string& name, int age, const std::string& breed)
: Animal(name, age), breed(breed) {
std::cout << "Dog构造函数: " << name << std::endl;
}
~Dog() override {
std::cout << "Dog析构函数: " << name << std::endl;
}
void makeSound() const override {
std::cout << name << " 汪汪叫" << std::endl;
}
void fetch() {
std::cout << name << " 正在捡球" << std::endl;
}
const std::string& getBreed() const { return breed; }
};
// 保护继承:降低基类成员访问权限
class ProtectedBase {
public:
int public_member = 1;
protected:
int protected_member = 2;
private:
int private_member = 3;
};
class ProtectedDerived : protected ProtectedBase {
// public_member 变为 protected
// protected_member 仍为 protected
// private_member 不可访问
public:
void test() {
public_member = 10; // 可以访问
protected_member = 20; // 可以访问
// private_member = 30; // 错误:不可访问
}
};
// 私有继承:实现"is-implemented-in-terms-of"关系
class PrivateDerived : private ProtectedBase {
// 所有成员变为private
public:
using ProtectedBase::public_member; // 恢复为public
};
```
## 多态的实现与虚函数机制
### 虚函数表原理
```cpp
// 虚函数表示例
class Base {
public:
virtual void func1() {
std::cout << "Base::func1()" << std::endl;
}
virtual void func2() {
std::cout << "Base::func2()" << std::endl;
}
void nonVirtual() {
std::cout << "Base::nonVirtual()" << std::endl;
}
};
class Derived : public Base {
public:
void func1() override {
std::cout << "Derived::func1()" << std::endl;
}
void func2() override {
std::cout << "Derived::func2()" << std::endl;
}
virtual void func3() {
std::cout << "Derived::func3()" << std::endl;
}
};
// 理解vptr和vtable
void explore_vtable() {
Derived d;
Base* bp = &d;
// 通过指针调用虚函数
bp->func1(); // 调用Derived::func1()
bp->func2(); // 调用Derived::func2()
// 对象调用
d.func1(); // 调用Derived::func1()
d.func3(); // 调用Derived::func3()
// 动态类型识别
if (typeid(*bp) == typeid(Derived)) {
std::cout << "bp指向Derived对象" << std::endl;
}
}
```
### 纯虚函数与抽象类
```cpp
// 抽象基类定义接口
class Shape {
protected:
std::string color;
double x, y;
public:
Shape(const std::string& color, double x, double y)
: color(color), x(x), y(y) {}
virtual ~Shape() = default;
// 纯虚函数:必须由派生类实现
virtual double area() const = 0;
virtual double perimeter() const = 0;
virtual void draw() const = 0;
// 非纯虚函数:提供默认实现
virtual void move(double dx, double dy) {
x += dx;
y += dy;
std::cout << "移动到 (" << x << ", " << y << ")" << std::endl;
}
// 具体函数
const std::string& getColor() const { return color; }
void setColor(const std::string& newColor) { color = newColor; }
// 虚析构函数确保正确清理
virtual void cleanup() {
std::cout << "清理Shape资源" << std::endl;
}
};
// 具体派生类
class Circle : public Shape {
private:
double radius;
public:
Circle(const std::string& color, double x, double y, double radius)
: Shape(color, x, y), radius(radius) {}
double area() const override {
return 3.14159 * radius * radius;
}
double perimeter() const override {
return 2 * 3.14159 * radius;
}
void draw() const override {
std::cout << "绘制圆形: 颜色=" << color
<< ", 位置=(" << x << "," << y
<< "), 半径=" << radius << std::endl;
}
void cleanup() override {
Shape::cleanup();
std::cout << "清理Circle额外资源" << std::endl;
}
double getRadius() const { return radius; }
void setRadius(double r) { radius = r; }
};
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(const std::string& color, double x, double y,
double width, double height)
: Shape(color, x, y), width(width), height(height) {}
double area() const override {
return width * height;
}
double perimeter() const override {
return 2 * (width + height);
}
void draw() const override {
std::cout << "绘制矩形: 颜色=" << color
<< ", 位置=(" << x << "," << y
<< "), 尺寸=" << width << "x" << height << std::endl;
}
void cleanup() override {
Shape::cleanup();
std::cout << "清理Rectangle额外资源" << std::endl;
}
void scale(double factor) {
width *= factor;
height *= factor;
std::cout << "缩放为: " << width << "x" << height << std::endl;
}
};
```
## 多重继承与虚继承
### 解决菱形继承问题
```cpp
// 菱形继承问题
class Character {
protected:
std::string name;
int health;
public:
Character(const std::string& name, int health)
: name(name), health(health) {}
virtual void display() const {
std::cout << "角色: " << name << ", 生命值: " << health << std::endl;
}
virtual ~Character() = default;
};
class Warrior : public virtual Character { // 虚继承
protected:
int strength;
public:
Warrior(const std::string& name, int health, int strength)
: Character(name, health), strength(strength) {}
void display() const override {
Character::display();
std::cout << "力量: " << strength << std::endl;
}
void attack() {
std::cout << name << " 使用武器攻击!" << std::endl;
}
};
class Mage : public virtual Character { // 虚继承
protected:
int mana;
public:
Mage(const std::string& name, int health, int mana)
: Character(name, health), mana(mana) {}
void display() const override {
Character::display();
std::cout << "魔法值: " << mana << std::endl;
}
void castSpell() {
std::cout << name << " 施放法术!" << std::endl;
}
};
// 多继承:同时继承Warrior和Mage
class BattleMage : public Warrior, public Mage {
private:
int battleMagicPower;
public:
BattleMage(const std::string& name, int health,
int strength, int mana, int battleMagicPower)
: Character(name, health), // 直接调用虚基类构造函数
Warrior(name, health, strength),
Mage(name, health, mana),
battleMagicPower(battleMagicPower) {}
void display() const override {
Warrior::display();
std::cout << "魔法值: " << mana << std::endl;
std::cout << "战斗魔法力量: " << battleMagicPower << std::endl;
}
void specialAttack() {
std::cout << name << " 发动特殊攻击!" << std::endl;
attack();
castSpell();
}
};
// 使用多重继承
void multiple_inheritance_demo() {
BattleMage bm("黑暗法师", 150, 80, 200, 100);
bm.display();
bm.specialAttack();
// 通过不同基类指针访问
Character* charPtr = &bm;
Warrior* warPtr = &bm;
Mage* magePtr = &bm;
charPtr->display(); // 多态调用
warPtr->attack();
magePtr->castSpell();
}
```
## 设计模式中的继承应用
### 工厂方法模式
```cpp
// 工厂方法模式示例
class Document {
public:
virtual ~Document() = default;
virtual void open() = 0;
virtual void save() = 0;
virtual void close() = 0;
virtual std::string getType() const = 0;
};
class WordDocument : public Document {
public:
void open() override {
std::cout << "打开Word文档" << std::endl;
}
void save() override {
std::cout << "保存Word文档" << std::endl;
}
void close() override {
std::cout << "关闭Word文档" << std::endl;
}
std::string getType() const override {
return "Word Document";
}
};
class ExcelDocument : public Document {
public:
void open() override {
std::cout << "打开Excel文档" << std::endl;
}
void save() override {
std::cout << "保存Excel文档" << std::endl;
}
void close() override {
std::cout << "关闭Excel文档" << std::endl;
}
std::string getType() const override {
return "Excel Document";
}
};
// 抽象创建者
class Application {
public:
virtual ~Application() = default;
// 工厂方法
virtual std::unique_ptr<Document> createDocument() = 0;
void newDocument() {
auto doc = createDocument();
std::cout << "创建 " << doc->getType() << std::endl;
doc->open();
// 处理文档...
doc->save();
doc->close();
}
virtual std::string getName() const = 0;
};
// 具体创建者
class WordApplication : public Application {
public:
std::unique_ptr<Document> createDocument() override {
return std::make_unique<WordDocument>();
}
std::string getName() const override {
return "Word Processor";
}
};
class ExcelApplication : public Application {
public:
std::unique_ptr<Document> createDocument() override {
return std::make_unique<ExcelDocument>();
}
std::string getName() const override {
return "Spreadsheet Application";
}
};
// 使用工厂方法
void factory_method_demo() {
std::unique_ptr<Application> app;
// 根据配置选择应用类型
std::string app_type = "word"; // 从配置读取
if (app_type == "word") {
app = std::make_unique<WordApplication>();
} else if (app_type == "excel") {
app = std::make_unique<ExcelApplication>();
}
if (app) {
std::cout << "启动: " << app->getName() << std::endl;
app->newDocument();
}
}
```
### 观察者模式
```cpp
// 观察者模式示例
class Observer {
public:
virtual ~Observer() = default;
virtual void update(const std::string& message) = 0;
virtual std::string getName() const = 0;
};
class Subject {
protected:
std::vector<Observer*> observers;
public:
virtual ~Subject() = default;
void attach(Observer* observer) {
observers.push_back(observer);
}
void detach(Observer* observer) {
observers.erase(
std::remove(observers.begin(), observers.end(), observer),
observers.end());
}
virtual void notify(const std::string& message) {
for (Observer* observer : observers) {
observer->update(message);
}
}
};
// 具体主题
class WeatherStation : public Subject {
private:
float temperature;
float humidity;
public:
void setMeasurements(float temp, float humidity) {
this->temperature = temp;
this->humidity = humidity;
std::string message =
"温度: " + std::to_string(temp) +
"℃, 湿度: " + std::to_string(humidity) + "%";
notify(message);
}
float getTemperature() const { return temperature; }
float getHumidity() const { return humidity; }
};
// 具体观察者
class Display : public Observer {
private:
std::string name;
public:
explicit Display(const std::string& name) : name(name) {}
void update(const std::string& message) override {
std::cout << name << " 显示: " << message << std::endl;
}
std::string getName() const override {
return name;
}
};
class Logger : public Observer {
private:
std::ofstream log_file;
public:
explicit Logger(const std::string& filename) {
<"wb.yunruiwater.cn"><"xb.sxyicheng.cn"><"yb.jsnjz.cn">
log_file.open(filename, std::ios::app);
}
~Logger() {
if (log_file.is_open()) {
log_file.close();
}
}
void update(const std::string& message) override {
if (log_file.is_open()) {
auto now = std::chrono::system_clock::now();
auto time = std::chrono::system_clock::to_time_t(now);
log_file << std::ctime(&time) << " - " << message << std::endl;
}
}
std::string getName() const override {
return "数据记录器";
}
};
```
## 现代C++中的继承特性
### final和override关键字
```cpp
// final和override使用
class BaseClass {
public:
virtual void func1() {
std::cout << "BaseClass::func1()" << std::endl;
}
virtual void func2() final { // 禁止派生类重写
std::cout << "BaseClass::func2()" << std::endl;
}
virtual void func3() {
std::cout << "BaseClass::func3()" << std::endl;
}
};
class DerivedClass : public BaseClass {
public:
void func1() override { // 明确表示重写
std::cout << "DerivedClass::func1()" << std::endl;
}
// 错误:不能重写final函数
// void func2() override { ... }
// 使用override确保正确重写
void func3() override {
std::cout << "DerivedClass::func3()" << std::endl;
}
};
// final类:禁止继承
class FinalClass final {
public:
void operation() {
std::cout << "FinalClass操作" << std::endl;
}
};
// 错误:不能继承final类
// class TryToInherit : public FinalClass { ... };
```
### 使用智能指针管理继承层次
```cpp
// 智能指针与继承
class Asset {
protected:
std::string id;
double value;
public:
Asset(const std::string& id, double value)
: id(id), value(value) {}
virtual ~Asset() = default;
virtual void display() const {
std::cout << "资产ID: " << id << ", 价值: $" << value << std::endl;
}
virtual std::unique_ptr<Asset> clone() const = 0;
virtual double calculateTax() const {
return value * 0.1; // 10%税
}
};
class RealEstate : public Asset {
private:
std::string address;
double squareMeters;
public:
RealEstate(const std::string& id, double value,
const std::string& address, double squareMeters)
: Asset(id, value), address(address),
squareMeters(squareMeters) {}
void display() const override {
Asset::display();
std::cout << "地址: " << address
<< ", 面积: " << squareMeters << "平方米" << std::endl;
}
std::unique_ptr<Asset> clone() const override {
return std::make_unique<RealEstate>(*this);
}
double calculateTax() const override {
return value * 0.05; // 房产税5%
}
};
class Stock : public Asset {
private:
std::string company;
int shares;
public:
Stock(const std::string& id, double value,
const std::string& company, int shares)
: Asset(id, value), company(company),
shares(shares) {}
void display() const override {
Asset::display();
std::cout << "公司: " << company
<< ", 股份: " << shares << std::endl;
}
std::unique_ptr<Asset> clone() const override {
return std::make_unique<Stock>(*this);
}
double calculateTax() const override {
return value * 0.15; // 股票税15%
}
};
// 资产管理器
class AssetManager {
private:
std::vector<std::unique_ptr<Asset>> assets;
public:
void addAsset(std::unique_ptr<Asset> asset) {
assets.push_back(std::move(asset));
}
void displayAll() const {
for (const auto& asset : assets) {
asset->display();
std::cout << "税费: $" << asset->calculateTax() << std::endl;
}
}
double calculateTotalValue() const {
double total = 0;
for (const auto& asset : assets) {
total += asset->value;
}
return total;
}
double calculateTotalTax() const {
double totalTax = 0;
for (const auto& asset : assets) {
totalTax += asset->calculateTax();
}
return totalTax;
}
// 克隆所有资产
std::unique_ptr<AssetManager> clone() const {
auto manager = std::make_unique<AssetManager>();
for (const auto& asset : assets) {
manager->addAsset(asset->clone());
}
return manager;
}
};
```
## 性能优化与最佳实践
### 虚函数调用开销分析
```cpp
// 虚函数性能对比
#include <chrono>
class NonVirtualBase {
public:
void operation() {
// 具体实现
}
};
class VirtualBase {
public:
virtual void operation() {
// 具体实现
}
};
void benchmark_virtual_calls() {
const int ITERATIONS = 100000000;
// 非虚函数调用测试
{
NonVirtualBase obj;
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < ITERATIONS; ++i) {
obj.operation();
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "非虚函数调用耗时: " << duration.count() << "ms" << std::endl;
}
// 虚函数调用测试
{
VirtualBase* ptr = new VirtualBase();
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < ITERATIONS; ++i) {
ptr->operation();
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "虚函数调用耗时: " << duration.count() << "ms" << std::endl;
delete ptr;
}
}
// 减少虚函数使用的情况
class OptimizedShape {
protected:
// 使用枚举替代运行时类型识别
enum class ShapeType {
CIRCLE,
RECTANGLE,
TRIANGLE
} type;
public:
explicit OptimizedShape(ShapeType t) : type(t) {}
// 使用非虚函数配合switch
double calculateArea() const {
switch (type) {
case ShapeType::CIRCLE:
return calculateCircleArea();
case ShapeType::RECTANGLE:
return calculateRectangleArea();
case ShapeType::TRIANGLE:
return calculateTriangleArea();
default:
return 0.0;
}
}
protected:
virtual double calculateCircleArea() const = 0;
virtual double calculateRectangleArea() const = 0;
virtual double calculateTriangleArea() const = 0;
};
```
### 继承层次设计原则
```cpp
// 遵循Liskov替换原则
class Bird {
public:
virtual ~Bird() = default;
virtual void fly() = 0;
virtual void eat() = 0;
};
class FlyingBird : public Bird {
public:
void fly() override {
std::cout << "飞行中..." << std::endl;
}
void eat() override {
std::cout << "吃东西" << std::endl;
}
};
class Penguin : public Bird {
public:
// 企鹅不会飞,违反LSP原则
void fly() override {
throw std::logic_error("企鹅不会飞!");
}
void eat() override {
std::cout << "吃鱼" << std::endl;
}
};
// 改进设计:遵循LSP
class BirdBase {
public:
virtual ~BirdBase() = default;
virtual void eat() = 0;
};
class FlyableBird : public BirdBase {
public:
virtual void fly() = 0;
};
class NonFlyableBird : public BirdBase {
// 没有fly方法
};
class Sparrow : public FlyableBird {
public:
void eat() override {
std::cout << "麻雀吃虫子" << std::endl;
}
void fly() override {
std::cout << "麻雀飞行" << std::endl;
}
};
class Ostrich : public NonFlyableBird {
public:
void eat() override {
std::cout << "鸵鸟吃植物" << std::endl;
}
};
```
## 实际应用:游戏实体系统
```cpp
// 游戏实体继承体系
class GameObject {
protected:
std::string name;
float x, y;
bool isActive;
public:
GameObject(const std::string& name, float x, float y)
: name(name), x(x), y(y), isActive(true) {}
virtual ~GameObject() = default;
virtual void update(float deltaTime) {
// 基础更新逻辑
}
virtual void render() const {
std::cout << "渲染对象: " << name
<< " 位置: (" << x << ", " << y << ")" << std::endl;
}
virtual void onCollision(GameObject* other) {
std::cout << name << " 与 " << other->name << " 碰撞" << std::endl;
}
const std::string& getName() const { return name; }
void setPosition(float newX, float newY) { x = newX; y = newY; }
bool getIsActive() const { return isActive; }
void setActive(bool active) { isActive = active; }
};
class PhysicsObject : public virtual GameObject {
protected:
float velocityX, velocityY;
float mass;
bool hasGravity;
public:
PhysicsObject(const std::string& name, float x, float y,
float mass, bool hasGravity = true)
: GameObject(name, x, y), velocityX(0), velocityY(0),
mass(mass), hasGravity(hasGravity) {}
void update(float deltaTime) override {
GameObject::update(deltaTime);
if (hasGravity) {
velocityY -= 9.8f * deltaTime; // 重力
}
x += velocityX * deltaTime;
y += velocityY * deltaTime;
}
void applyForce(float forceX, float forceY) {
velocityX += forceX / mass;
velocityY += forceY / mass;
}
};
class RenderableObject : public virtual GameObject {
<"zc.csxthr.com"><"i5.zhaiLimao.com"><"rt.yunruiwater.cn">
protected:
std::string texturePath;
float width, height;
public:
RenderableObject(const std::string& name, float x, float y,
const std::string& texturePath, float width, float height)
: GameObject(name, x, y), texturePath(texturePath),
width(width), height(height) {}
void render() const override {
std::cout << "渲染纹理: " << texturePath
<< " 位置: (" << x << ", " << y << ")"
<< " 尺寸: " << width << "x" << height << std::endl;
}
void setTexture(const std::string& newTexture) {
texturePath = newTexture;
}
void setSize(float w, float h) {
width = w;
height = h;
}
};
// 组合继承:物理可渲染对象
class PhysicalRenderable : public PhysicsObject, public RenderableObject {
public:
PhysicalRenderable(const std::string& name, float x, float y,
float mass, const std::string& texturePath,
float width, float height)
: GameObject(name, x, y), // 虚基类初始化
PhysicsObject(name, x, y, mass),
RenderableObject(name, x, y, texturePath, width, height) {}
void update(float deltaTime) override {
PhysicsObject::update(deltaTime);
// 渲染相关的更新...
}
void render() const override {
RenderableObject::render();
// 显示物理信息
std::cout << "速度: (" << velocityX << ", " << velocityY << ")" << std::endl;
}
};
// 游戏管理器
class GameManager {
private:
std::vector<std::unique_ptr<GameObject>> gameObjects;
public:
void addObject(std::unique_ptr<GameObject> obj) {
gameObjects.push_back(std::move(obj));
}
void updateAll(float deltaTime) {
for (auto& obj : gameObjects) {
if (obj->getIsActive()) {
obj->update(deltaTime);
}
}
}
void renderAll() const {
for (const auto& obj : gameObjects) {
if (obj->getIsActive()) {
obj->render();
}
}
}
GameObject* findObject(const std::string& name) const {
for (const auto& obj : gameObjects) {
if (obj->getName() == name) {
return obj.get();
}
}
return nullptr;
}
};
```
C++继承与多态机制为构建可扩展、可维护的软件系统提供了强大支持。通过合理运用继承层次、虚函数机制和设计模式,可以实现代码的高效复用和灵活扩展。理解虚函数表原理、掌握多重继承的正确使用方式、遵循面向对象设计原则,是编写高质量C++代码的关键。结合现代C++特性如智能指针、final/override关键字,可以构建出既安全又高效的面向对象系统。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19545/viewspace-3108969/ ,如需转载,请注明出处,否则将追究法律责任。