You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++使用std::list排序Student对象时遇类型限定符兼容错误排查

问题原因及解决方法

1. 成员函数未声明为const

你的lambda表达式中接收的是const Students&类型的对象,但调用的getStudentNumber()等成员函数没有被声明为const成员函数。在C++中,const对象只能调用const修饰的成员函数,否则编译器会抛出“类型限定符不兼容”的错误。

修复方法:

将所有getter成员函数添加const修饰符,示例如下:

int getStudentNumber() const {
    return this->studentNumber;
}

string getStudentName() const {
    return this->studentName;
}

// 其余getGrade1到getTotal函数都需要添加const修饰

2. 未重载<运算符

代码中当学号相同时,尝试使用student1 < student2进行比较,但Students类没有重载<运算符,这会导致编译错误。

修复方法:

在Students类的public区域添加<运算符的重载,可自定义排序规则(比如按姓名字典序):

bool operator<(const Students& other) const {
    return this->studentName < other.studentName;
}

完整修复后的代码片段

修改后的Students类

class Students {
    int studentNumber;
    string studentName;
    int grade1;
    int grade2;
    int grade3;
    int grade4;
    int grade5;
    int total;
public:
    void setStudent(int number, string name, int g1, int g2, int g3, int g4, int g5, int total) {
        this->studentNumber = number;
        this->studentName = name;
        this->grade1 = g1;
        this->grade2 = g2;
        this->grade3 = g3;
        this->grade4 = g4;
        this->grade5 = g5;
        this->total = total;
    }

    int getStudentNumber() const {
        return this->studentNumber;
    }

    string getStudentName() const {
        return this->studentName;
    }

    int getGrade1() const {
        return this->grade1;
    }

    int getGrade2() const {
        return this->grade2;
    }

    int getGrade3() const {
        return this->grade3;
    }

    int getGrade4() const {
        return this->grade4;
    }

    int getGrade5() const {
        return this->grade5;
    }

    int getTotal() const {
        return this->total;
    }

    // 重载<运算符,自定义学号相同时的排序规则
    bool operator<(const Students& other) const {
        return studentName < other.studentName;
    }
};

可正常运行的排序代码

listOfStudents.sort([](const Students& student1, const Students& student2)
    {
        if (student1.getStudentNumber() == student2.getStudentNumber())
            return student1 < student2;
        return student1.getStudentNumber() < student2.getStudentNumber();
    });

内容的提问来源于stack exchange,提问作者Bedivere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 17:05:28