[英]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;
};
是n1
和n2
都是指針。 即使它們是指向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.