1、直接放
std::set<NetworkInfo> networks;
其中NetworkInfo是一个自定义结构体
//网络信息配置结构体
struct NetworkInfo
{
bool isRuning; //是否正在运行
Protocol netWorkProtocol; //协议
QString aimIP; //目标IP
quint16 aimPort; //目标端口
QString localIp; //本地IP
quint16 localPort; //本地端口
NetworkInfo& operator = (const NetworkInfo& in){
isRuning = in.isRuning;
netWorkProtocol = in.netWorkProtocol;
aimIP = in.aimIP;
aimPort = in.aimPort;
localIp = in.localIp;
localPort = in.localPort;
return *this;
}
};
2、编译报错
D:\Soft\Qt5.10\Tools\mingw530_32\i686-w64-mingw32\include\c++\bits\stl_function.h:387: error: no match for 'operator<' (operand types are 'const NetworkInfo' and 'const NetworkInfo')
{ return __x < __y; }
^
3、原因分析
因为插入的类型是自定义的,不是基本类型(基本类型有默认的排序准则),因此需要重载 < 运算符
https://blog.csdn.net/cpohui/article/details/79826908
4、解决
//网络信息配置结构体
struct NetworkInfo
{
bool isRuning; //是否正在运行
Protocol netWorkProtocol; //协议
QString aimIP; //目标IP
quint16 aimPort; //目标端口
QString localIp; //本地IP
quint16 localPort; //本地端口
NetworkInfo& operator = (const NetworkInfo& in){
isRuning = in.isRuning;
netWorkProtocol = in.netWorkProtocol;
aimIP = in.aimIP;
aimPort = in.aimPort;
localIp = in.localIp;
localPort = in.localPort;
return *this;
}
friend bool operator<(const NetworkInfo & x,const NetworkInfo & y)
{
return x.aimPort<y.aimPort;
}
};
注意这个friend,必须加,不然会报错:
must take exactly one argument
原因:
是用成员方式重载运算符, 不能改变参数的个数 ,二元运算符用成员重载时, 只需要一个参数, 另一个参数由this指针传入 。如果需要两个参数,那么可以在类外面定义,然后在类里声明为友元。
https://blog.csdn.net/chengqiaoyahaixuyush/article/details/24402151