首页 > 解决方案 > <链表C ++中结构成员的运算符重载

问题描述

所以基本上我有我的结构,它在将数据分配给链表的值之前保留数据,并帮助我稍后检索它

struct Student
{

private:

    string surname ;
    string names ;
    int index;
    float mark;
}

这是我插入排序链表的实现

template<typename T>
void List<T>::insert(T v)
{
    Node* pred = nullptr;
    Node* succ = head;

    while(succ != nullptr && succ->value < v) <- here
    {
        pred = succ;
        succ = succ->next;
    }
...

我的问题是我需要按索引对其进行排序,而我的 < 运算符重载的实现似乎都不起作用

bool operator<(const Student&){
    return  next->index < this->index;}

我正在对 == 或 + 之类的运算符进行一些重载,但从不 <,有人可以给我建议它的外观吗?

标签: c++structlinked-listoperator-overloading

解决方案


indexprivate,这意味着您需要将其设为成员函数或将其声明为friend.

struct Student {

    bool operator<(const Student& other) const {
        return index < other.index;
    }

private:
    string surname;
    string names;
    int index;
    float mark;
};

您可以指定this->index而不是 just index,但大多数时候这不是必需的。

另外,作为旁注,如果您使用的是 C++ 20,我建议重载spaceship 运算符,因为这将自动为所有比较运算符(和除外)生成适当的定义==!=

    auto operator<=>(const Student& other) {
        return index <=> other.index;
    }

推荐阅读