c++ - Operator== 抽象类和 shared_ptr 的重载

标签 c++ c++11 polymorphism operator-overloading shared-ptr

我想使用 std::findshared_ptr 的列表中一个抽象类,但我收到一个错误。有没有办法比较两个 shared_ptr通过在 std::find 中取消引用它们?

有没有可能交个 friend 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
    }
};

Error C2679 binary '==': no operator found which takes a right-hand operand of type 'const Point' (or there is no acceptable conversion)

备注:Point已经有 operator== .

最佳答案

问题:

find() 旨在在迭代器范围内找到一个精确的

您已经定义了一个 operator== 来比较一个 A 和一个 Point。但是您的列表不包含 A 对象,而是包含指向 A 对象的共享指针。不幸的是,将共享指针与 Point 进行比较并没有定义。这种不匹配会导致您报告的错误。

解决方案:

一个简单的解决方案是使用 find_if() 而不是 find():它不寻找精确值,而是寻找谓词变为真:

   const auto & f = find_if(l.begin(), l.end(),[p](shared_ptr<A> &a){ return *a==p; });

关于c++ - Operator== 抽象类和 shared_ptr 的重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34662996/

相关文章:

c++ - 结构中的省略号

c++ - 当调用具有等待条件变量的线程对象的析构函数时会发生什么?

c++ - 函数可以接受抽象基类作为参数吗?

c++ - 有没有办法专门化继承对象的一般方法

c++ - 将重载函数指针作为参数传递给重载模板函数

c++ - 在声子 (Qt) 中解析 .pls/.m3u

C++ SPDLOG编译错误: variable or field ‘set_error_handler’ declared void

c++ - 泛型枚举和其他类型的重载模板函数

c++ - 如何使用新的 c++0x regex 对象在字符串中重复匹配?

ruby-on-rails - 多态模型中的单个记录可以同时属于两个(或更多)模型吗?