繁体   English   中英

在结构外重载运算符

[英]overloading operator outside of struct

我有一个struct ,想实现一set指针。 因此,我尝试重载operator <以使其实现。 这里的一个限制是我无权在struct定义中编写重载代码。 我该如何在结构之外进行操作?

这是我到目前为止的内容:

#include<iostream>
#include<set>
#include<vector>

using namespace std;

struct mystruct {
    int label;
    vector<mystruct *> neighbors;
};
bool operator < (mystruct * n1, mystruct* n2) {
    return n1 -> label < n2 -> label;
};
int main() {
    set<mystruct *> s;
    return 0;
}

错误消息是

错误:重载的“ operator <”必须至少具有一个类或枚举类型的参数

问题所在

bool operator < (mystruct * n1, mystruct* n2) {
    return n1 -> label < n2 -> label;
};

n1n2都是指针。 即使它们是指向mystruct指针,它们仍然仅仅是指针,并且您不能在内置指针时重载运算符。解决此问题的最简单方法是改为使用引用并使用诸如

bool operator < (const mystruct& n1, const mystruct7 n2) {
    return n.label < n2.label;
};

int main() {
    set<mystruct> s;
    return 0;
}

如果无法做到这一点,则需要为std::set提供一个比较函子,并使用该函式代替operator < 看起来像

struct mystruct_pointer_comp
{
    bool operator ()(mystruct * n1, mystruct* n2) {
        return n1->label < n2->label;
    };
}

int main() {
    set<mystruct *, mystruct_pointer_comp> s;
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM