我正在尝试创建Point类的一组自定义对象
point.h
#ifndef POINT_H
#define POINT_H
class Point
{
float x_coordinate,y_coordinate;
public:
Point(float x, float y):x_coordinate(x),y_coordinate(y)
{}
float get_x()
{
return x_coordinate;
}
float get_y()
{
return y_coordinate;
}
bool operator==(Point rhs)
{
if( ((int)x_coordinate == (int)rhs.get_x()) && ((int)y_coordinate == (int)rhs.get_y()) )
return true;
else return false;
}
bool operator<(Point rhs)
{
if((int)x_coordinate < (int)rhs.get_x())
return true;
else return false;
}
};
#endif
Run Code Online (Sandbox Code Playgroud)
我刚开始写驱动程序
#include<iostream>
#include<set>
#include "point.h"
using namespace std;
int main()
{
Point p1(-10,-10),p2(-10,10),p3(10,10),p4(10,-10);
set<Point> points_set = set<Point>();
points_set.insert(p1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是我在编译期间遇到这个错误,我已经重载了比较和相等运算符,我还需要做些什么才能让它工作?
In file included from /usr/include/c++/4.6/string:50:0,
from /usr/include/c++/4.6/bits/locale_classes.h:42,
from /usr/include/c++/4.6/bits/ios_base.h:43,
from /usr/include/c++/4.6/ios:43,
from /usr/include/c++/4.6/ostream:40,
from /usr/include/c++/4.6/iostream:40,
from driver.cpp:1:
/usr/include/c++/4.6/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Point]’:
/usr/include/c++/4.6/bits/stl_tree.h:1267:4: instantiated from ‘std::pair<std::_Rb_tree_iterator<_Val>, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(const _Val&) [with _Key = Point, _Val = Point, _KeyOfValue = std::_Identity<Point>, _Compare = std::less<Point>, _Alloc = std::allocator<Point>]’
/usr/include/c++/4.6/bits/stl_set.h:410:29: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, _Key, std::_Identity<_Key>, _Compare, typename _Alloc::rebind<_Key>::other>::const_iterator, bool> std::set<_Key, _Compare, _Alloc>::insert(const value_type&) [with _Key = Point, _Compare = std::less<Point>, _Alloc = std::allocator<Point>, typename std::_Rb_tree<_Key, _Key, std::_Identity<_Key>, _Compare, typename _Alloc::rebind<_Key>::other>::const_iterator = std::_Rb_tree_const_iterator<Point>, std::set<_Key, _Compare, _Alloc>::value_type = Point]’
driver.cpp:12:25: instantiated from here
/usr/include/c++/4.6/bits/stl_function.h:236:22: error: passing ‘const Point’ as ‘this’ argument of ‘bool Point::operator<(Point)’ discards qualifiers [-fpermissive]
Run Code Online (Sandbox Code Playgroud)
float get_x() const { ... }
float get_y() const { ... }
bool operator==(Point const& rhs) const { ... }
bool operator<(Point const& rhs) const { ... }
Run Code Online (Sandbox Code Playgroud)
你const在参数和方法本身中都缺少所有这些.
注意:我不确定operator<用于a中项目的要求是什么set,但是你提供的项目非常弱.