类的创建和使用模板
封装数据与行为——面向对象编程的基础
类
class
封装
构造函数
GESP6
#include <bits/stdc++.h>
using namespace std;
class Student {
private:
string name;
int age;
double score;
public:
// 构造函数
Student(string n, int a, double s) : name(n), age(a), score(s) {}
// 默认构造函数
Student() : name(""), age(0), score(0.0) {}
// 成员函数
void printInfo() {
cout << name << " " << age << " " << score << endl;
}
// getter/setter
string getName() const { return name; }
void setScore(double s) { score = s; }
// 运算符重载
bool operator<(const Student &o) const {
return score > o.score; // 按分数降序
}
};
int main() {
Student s1("小明", 12, 95.5);
Student s2("小红", 11, 98.0);
s1.printInfo();
vector<Student> stu;
stu.push_back(s1);
stu.push_back(s2);
sort(stu.begin(), stu.end());
for (auto &s : stu) s.printInfo();
return 0;
}
📖 要点说明
private私有成员,public公开接口- 构造函数初始化列表
: name(n), age(a)更高效 const成员函数承诺不修改对象- 运算符重载让类可用 sort/set/map
⚠️ 常见错误
- 构造函数忘初始化所有成员
- sort 比较函数不是严格弱序
- const 成员函数内修改成员变量