前言
这里只是简单列出C++中面向对象编程的知识点
一、概述
面向对象编程(OOP)是C++的核心范式,通过封装、继承、多态三大特性构建程序结构。C++在C语言基础上添加了类等面向对象特性,既支持过程化编程也支持面向对象编程,具有高度的灵活性和性能。
二、核心特性详解
2.1 类与对象(封装)
2.1.1 基本类定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Person { private: string name; int age; public: Person(string n, int a) : name(n), age(a) {} void introduce() { cout << "I'm " << name << ", " << age << " years old." << endl; } void setAge(int a) { age = a; } int getAge() const { return age; } };
|
2.1.2 特殊成员函数
1 2 3 4 5 6 7 8 9
| class Example { public: Example(); Example(const Example&); Example& operator=(const Example&); ~Example(); Example(Example&&); Example& operator=(Example&&); };
|
2.2 继承与派生
2.2.1 继承基础
1 2 3 4 5 6 7 8 9 10 11 12
| class Student : public Person { private: int grade; public: Student(string n, int a, int g) : Person(n, a), grade(g) {} void introduce() { Person::introduce(); cout << "Grade: " << grade << endl; } };
|
2.2.2 继承类型
| 继承方式 |
基类public成员 |
基类protected成员 |
基类private成员 |
| public |
public |
protected |
不可访问 |
| protected |
protected |
protected |
不可访问 |
| private |
private |
private |
不可访问 |
2.3 多态与虚函数
2.3.1 虚函数机制
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Shape { public: virtual double area() const = 0; virtual ~Shape() {} };
class Circle : public Shape { double radius; public: double area() const override { return 3.14 * radius * radius; } };
|
2.3.2 多态应用
1 2 3 4 5 6 7
| void printArea(const Shape& shape) { cout << "Area: " << shape.area() << endl; }
Circle c(5.0); printArea(c);
|
2.4 运算符重载
1 2 3 4 5 6 7 8 9 10 11 12
| class Vector { double x, y; public: Vector operator+(const Vector& other) const { return Vector(x + other.x, y + other.y); } friend ostream& operator<<(ostream& os, const Vector& v) { return os << "(" << v.x << ", " << v.y << ")"; } };
|
2.5 友元与静态成员
1 2 3 4 5 6 7 8 9 10 11 12 13
| class BankAccount { private: double balance; static int totalAccounts; public: friend class BankManager; static int getTotalAccounts() { return totalAccounts; } }; int BankAccount::totalAccounts = 0;
|
三、高级特性
3.1 多重继承
1 2 3 4
| class TA : public Teacher, public Student { };
|
3.2 RTTI(运行时类型识别)
1 2 3 4
| Base* ptr = new Derived(); if (Derived* d = dynamic_cast<Derived*>(ptr)) { }
|
3.3 现代C++特性(C++11/14/17)
3.3.1 override/final
1 2 3 4 5 6 7 8 9
| class Base { public: virtual void foo() final; };
class Derived : public Base { public: void foo() override; };
|
3.3.2 移动语义
1 2 3 4 5 6 7 8
| class ResourceHolder { int* data; public: ResourceHolder(ResourceHolder&& other) noexcept : data(other.data) { other.data = nullptr; } };
|
四、总结
4.1 面向对象优势
- 封装:隐藏实现细节,提供清晰接口
- 继承:代码复用和层次化设计
- 多态:统一接口,不同实现
4.2 最佳实践建议
- 优先使用组合而非继承
- 遵循单一职责原则
- 为多态基类声明虚析构函数
- 避免过度使用友元
- 合理使用const成员函数
- 注意对象生命周期管理
- 使用智能指针管理资源
版权声明: 此文章版权归曦曦所有,如有转载,请注明来自原作者