C++面向对象特性在项目中的体现

面向对象的基本特性

  1. 封装(Encapsulation):将数据和操作封装在类中,通过访问控制保护数据。
  2. 继承(Inheritance):允许一个类继承另一个类的属性和方法,增强代码的重用性和扩展性。
  3. 多态(Polymorphism):通过函数重载和虚函数,实现接口的多态性,使得同一接口可以有不同的实现。

项目中的具体体现

假设我们有一个涉及几何图形绘制和计算的项目。在这个项目中,我们可以很好地利用面向对象的特性。

项目示例
1. 封装

封装允许我们将数据和相关操作封装在类中,保护数据的私密性。

class Shape {
private:
    std::string color;

public:
    void setColor(const std::string& col) {
        color = col;
    }

    std::string getColor() const {
        return color;
    }

    virtual double area() const = 0; // 纯虚函数,定义接口
};

2. 继承

继承可以让我们定义具体的图形类,如圆和矩形,继承自基础的 Shape 类。

class Circle : public Shape {
private:
    double radius;

public:
    Circle(double r) : radius(r) {}

    double area() const override {
        return 3.14159 * radius * radius;
    }
};

class Rectangle : public Shape {
private:
    double width, height;

public:
    Rectangle(double w, double h) : width(w), height(h) {}

    double area() const override {
        return width * height;
    }
};

3. 多态

多态性使得我们可以通过基类指针或引用来操作不同的派生类对象,实现灵活的接口调用。

#include <iostream>
#include <vector>
#include <memory>

int main() {
    std::vector<std::shared_ptr<Shape>> shapes;
    shapes.push_back(std::make_shared<Circle>(10));
    shapes.push_back(std::make_shared<Rectangle>(5, 10));

    for (const auto& shape : shapes) {
        std::cout << "Area: " << shape->area() << std::endl;
    }

    return 0;
}
  • 21
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值