gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:23:06 32 4
gpt4 key购买 nike

我想使用 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/

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