创建集时出错

M.A*_*M.A 3 c++ set

我想知道为什么我无法创建一个集合.我收到以下错误

这是我的代码.

Point.cpp我的Point类

bool Point::operator<(const Point& p2)const {
return p21.length < p2.getScalarValue();
}

bool Point::operator>(const Point p2) {
bool result;
result = length > p2.getScalarValue();
return result;
Run Code Online (Sandbox Code Playgroud)

}

在我的main.cpp中

set<Point> s_p2;
Point tempp2;
s_p2.insert(tempp2);
Run Code Online (Sandbox Code Playgroud)

按照您的输入后,我编辑了代码,我有以下错误

Point.cpp:56:46:错误:将'const Point'作为'double Point :: getScalarValue()'的'this'参数传递,丢弃限定符[-fpermissive]

这是因为我有两个比较陈述吗?

jua*_*nza 5

没有std :: set :: insert重载,它将bool作为第二个参数.你可以像这样插入:

s_p2.insert(tempp2);
Run Code Online (Sandbox Code Playgroud)

operator<通过使它成为一个const方法,你可以改进你的const参考参数:

class Point {
  // as before
  bool operator<(const Point& p) const;
};  //                            ^ here, const method

bool Point::operator<(const Point& p2) const {
  return length < p2.length;
}
Run Code Online (Sandbox Code Playgroud)

您也可以选择将其设为非成员函数:

bool operator<(const Point& lhs, const Point& rhs) {
  return lhs.getScalarValue() < rhs.getScalarValue();
}
Run Code Online (Sandbox Code Playgroud)

这具有与LHS和RHS完全对称的优点.如果您有隐式转换Point或从中派生,则这很重要Point.