面向对象的基本特性
- 封装(Encapsulation):将数据和操作封装在类中,通过访问控制保护数据。
- 继承(Inheritance):允许一个类继承另一个类的属性和方法,增强代码的重用性和扩展性。
- 多态(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;
}