【发布时间】:2016-04-12 07:21:27
【问题描述】:
我想在一个抽象类的shared_ptr 列表中使用std::find,但出现错误。有没有办法通过在std::find 中取消引用来比较两个shared_ptr?
是否有可能交一个朋友operator== 重载shared_ptr<A>?
小例子:
#include "point.h"
#include <list>
#include <algorithm>
#include <memory>
using namespace std;
class A {
protected:
Point loc;
public:
virtual void foo() = 0;
virtual bool operator==(const Point& rhs) const = 0;
};
class B: public A {
virtual void foo() override{}
virtual bool operator==(const Point& rhs) const override {
return rhs == loc;
}
};
class C {
list<shared_ptr<A>> l;
void bar(Point & p) {
const auto & f = find(l.begin(), l.end(), p); //<-- error is from here
}
};
错误 C2679 二进制“==”:未找到采用“const Point”类型右侧操作数的运算符(或没有可接受的转换)
注意:Point 已经有 operator==。
【问题讨论】:
-
但它是在 shared_ptr::operator == () 方面比较的
-
@DieterLücking 我不明白。
-
尝试定义
bool operator==(const std::shared_ptr<A> &sp, const Point &point){return ((*sp) == point);} -
@Rames 说它的参数太多了。
-
@kuhaku 你在课外声明了吗?它不能是类成员。
标签: c++ c++11 polymorphism operator-overloading shared-ptr