gpt4 book ai didi

c++ - 错误 C2678 : binary '==' : no operator found which takes a left-hand operand of type (or there is no acceptable conversion)

转载 作者:可可西里 更新时间:2023-11-01 16:35:29 33 4
gpt4 key购买 nike

我正在尝试编译以下代码:

#include <boost/geometry/geometries/point_xy.hpp>

#include <iostream>
#include <utility>

typedef boost::geometry::model::d2::point_xy<long> Point;
typedef std::pair<Point, Point> Vector;

bool operator==(const Point& p1, const Point& p2) {
return p1.x() == p2.x() && p1.y() == p2.y();
}

int main() {
Vector vec1(Point(0,0), Point(1,1));
Vector vec2(Point(0,0), Point(1,2));
std::cout << ((vec1 == vec2) == false) << std::endl;
std::cout << ((vec1 == vec1) == true) << std::endl;
}

VS2012 C++ 编译器返回以下编译错误:

...VC\include\utility(219): error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const Point' (or there is no acceptable conversion)

GCC C++ 编译器返回以下编译错误:

/usr/include/c++/4.8/bits/stl_pair.h:

In instantiation of ‘bool std::operator==(const std::pair<_T1, _T2>&, const std::pair<_T1, _T2>&) [with _T1 = boost::geometry::model::d2::point_xy; _T2 = boost::geometry::model::d2::point_xy]’:

test.cpp:22:28: required from here /usr/include/c++/4.8/bits/stl_pair.h:215:51: error:

no match for ‘operator==’ (operand types are ‘const boost::geometry::model::d2::point_xy’ and ‘const boost::geometry::model::d2::point_xy’) { return __x.first == __y.first && __x.second == __y.second; }

如果我为 Vector 重载 == 运算符,错误就会消失:

bool operator==(const Vector& v1, const Vector& v2) {
return v1.first == v2.first && v1.second == v2.second;
}

最佳答案

失败的原因是 std::pairoperator == 使用 == 来比较 pair 的成员,依次使用 argument-dependent lookup (ADL)为他们找到合适的 operator ==。但是您在错误的命名空间中提供了重载,因为 Point 实际上是 ::boost::geometry::model::d2 中某些内容的 typedef,而不是在 :: 中。

如果您将运算符移动到正确的命名空间(无论如何这是个好主意),它会起作用:

#include <boost/geometry/geometries/point_xy.hpp>

#include <iostream>
#include <utility>

typedef boost::geometry::model::d2::point_xy<long> Point;
typedef std::pair<Point, Point> Vector;

namespace boost { namespace geometry { namespace model { namespace d2 {

bool operator==(const Point& p1, const Point& p2) {
return p1.x() == p2.x() && p1.y() == p2.y();
}

} } } }


int main() {
Vector vec1(Point(0,0), Point(1,1));
Vector vec2(Point(0,0), Point(1,2));
std::cout << ((vec1 == vec2) == false) << std::endl;
std::cout << ((vec1 == vec1) == true) << std::endl;
}

Live example

关于c++ - 错误 C2678 : binary '==' : no operator found which takes a left-hand operand of type (or there is no acceptable conversion),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26273570/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com