1. 为什么需要类和对象?
我第一次接触C++的类和对象概念时,内心充满了困惑——为什么已经有了结构体(struct)还要引入类(class)?这个问题困扰了我很久,直到在实际项目中遇到了数据管理的难题。
假设我们要开发一个学生管理系统。用传统的过程式编程方法,我们可能会这样定义:
cpp复制struct Student {
char name[20];
int age;
float score;
};
void printStudentInfo(Student s) {
printf("Name: %s, Age: %d, Score: %.1f\n", s.name, s.age, s.score);
}
void setStudentScore(Student* s, float newScore) {
if(newScore >= 0 && newScore <= 100) {
s->score = newScore;
}
}
这种方式存在几个明显问题:
- 数据和操作分离,容易造成命名冲突
- 无法控制对数据的直接访问(比如可以直接修改s.score = -50)
- 相关函数散落在各处,难以维护
2. 类的基本定义与封装特性
2.1 类的声明与实现
C++中的类定义解决了上述所有问题。我们把上面的例子用类重写:
cpp复制class Student {
private:
string name;
int age;
float score;
public:
// 构造函数
Student(string n, int a, float s) : name(n), age(a), score(s) {}
void printInfo() {
cout << "Name: " << name << ", Age: " << age
<< ", Score: " << fixed << setprecision(1) << score << endl;
}
void setScore(float newScore
