1. C++类与对象核心概念回顾
在C++编程中,类和对象是面向对象编程的基石。类可以看作是一个蓝图或模板,它定义了对象的形式和行为。而对象则是类的具体实例,就像根据建筑设计图建造出来的实际房屋。
类的基本结构包含两个关键部分:
- 成员变量(属性):描述对象的状态特征
- 成员函数(方法):定义对象的行为能力
cpp复制class Car {
public:
// 成员变量
string brand;
string model;
int year;
// 成员函数
void honk() {
cout << "Beep beep!" << endl;
}
};
这个简单的Car类定义了三个成员变量和一个成员函数。public关键字表示这些成员在类的外部是可访问的。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 类成员的访问控制深入解析
C++提供了三种访问修饰符来控制类成员的可见性:
2.1 public访问权限
public成员在类的外部可以直接访问,通常用于定义类的接口部分。例如:
cpp复制class Student {
public:
string name; // 公有成员变量
void display() { // 公有成员函数
cout << "Name: " << name << endl;
}
};
int main() {
Student s1;
s1.name = "Alice"; // 可以直接访问
s1.display(); // 可以直接调用
return 0;
}
2.2 private访问权限
private成员只能在类的内部访问,这是封装性的重要体现。默认情况下,类的成员都是private的。
cpp复制class BankAccount {
private:
double balance; // 私有成员变量
public:
void deposit(double amount) {
if (amount > 0) {
balance += amount; // 可以在成员函数中访问私有成员
}
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount acc;
// acc.balance = 1000; // 错误!不能直接访问私有成员
acc.deposit(500); // 必须通过公有接口操作
cout << acc.getBalance() << endl;
return 0;
}
2.3 protected访问权限
protected成员在继承体系中特别重要,它们对派生类可见,但对类外部不可见。
cpp复制class Shape {
protected:
int width, height;
public:
void setDimensions(int w, int h) {
width = w;
height = h;
}
};
class Rectangle : public Shape {
public:
int area() {
return width * height; // 派生类可以访问基类的protected成员
}
};
3. 构造函数与析构函数实战技巧
3.1 构造函数的多种形式
构造函数在对象创建时自动调用,用于初始化对象。C++支持多种构造函数形式:
cpp复制class Point {
private:
int x, y;
public:
// 默认构造函数
Point() : x(0), y(0) {
cout << "Default constructor called" << endl;
}
// 参数化构造函数
Point(int a, int b) : x(a), y(b) {
cout << "Parameterized constructor called" << endl;
}
// 拷贝构造函数
Point(const Point &p) : x(p.x), y(p.y) {
cout << "Copy constructor called" << endl;
}
void display() {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
Point p1; // 调用默认构造函数
Point p2(3, 4); // 调用参数化构造函数
Point p3 = p2; // 调用拷贝构造函数
p1.display();
p2.display();
p3.display();
return 0;
}
3.2 析构函数的正确使用
析构函数在对象销毁时自动调用,用于释放资源。一个类只能有一个析构函数。
cpp复制class FileHandler {
private:
FILE *file;
public:
FileHandler(const char* filename) {
file = fopen(filename, "r");
if (!file) {
cerr << "Failed to open file" << endl;
}
}
~FileHandler() {
if (file) {
fclose(
