1. C++类与对象核心概念解析
在C++编程中,类和对象是最基础也是最重要的概念之一。类可以看作是一个蓝图或模板,它定义了一类对象的属性和行为。而对象则是根据这个蓝图创建的具体实例。
1.1 类的定义与结构
类的定义使用class关键字,后跟类名和一对大括号。类中可以包含两种主要成员:
- 成员变量:描述对象的属性或状态
- 成员函数:定义对象的行为或操作
cpp复制class Stack {
public:
// 成员函数
void Push(int x) {
// 实现压栈操作
}
// 成员变量
int* a;
int top;
int capacity;
};
在实际开发中,为了区分成员变量和局部变量,通常会给成员变量添加特殊前缀,如_或m:
cpp复制class Date {
public:
void Init(int year, int month, int day) {
_year = year;
_month = month;
_day = day;
}
private:
int _year; // 使用下划线前缀
int _month;
int _day;
};
1.2 访问控制与封装
C++通过访问限定符实现封装,这是面向对象编程的重要特性:
- public:公有成员,类外可以直接访问
- private:私有成员,只能在类内部访问
- protected:保护成员,类内和派生类中可以访问
cpp复制class Stack {
private: // 私有成员
int* _array;
size_t _capacity;
size_t _top;
public: // 公有接口
void Init(int n = 4) {
_array = (int*)malloc(sizeof(int) * n);
_capacity = n;
_top = 0;
