返回首页 C++ 模板

类的创建和使用模板

封装数据与行为——面向对象编程的基础

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;
}

📖 要点说明

⚠️ 常见错误