C++ == 运算符,用于使用 shared_ptr 的抽象基类的子级

C++ == operator for child of abstract base class using shared_ptr

本文关键字:抽象 ptr 基类 shared 运算符 用于 C++      更新时间:2023-10-16

我得到了一个抽象基类"Parent",其中包含一个纯虚拟方法和一个实现此方法的子类"Child"和一个成员"值"。我将子类的对象实例化为shared_ptr作为动态绑定的一种方式。我在这里使用shared_ptr而不是引用,因为我将这些对象存储在 std::vector 中。

现在我想比较源代码底部定义的两个对象"someObject"和"otherObject"。因此,我覆盖了相应 Child 类中的 == 运算符。但是,只调用shared_ptr的 == 运算符。我可以对后面的动态绑定对象进行比较吗?

/*
* Parent.h
*/
class Parent{
public:
    virtual ~Parent(){};
    virtual void someFunction() = 0;
};

/*
* Child.h
*/
class Child : public Base{
private:
    short value;
public:
    Child(short value);
    virtual ~Child();
    bool operator==(const Child &other) const;
    void someFunction();
};

/*
* Child.cpp
*/
#include "Child.h"
Child::Child(short value):value(value){}
Child::~Child() {}
void Child::someFunction(){...}
bool Child::operator==(const Child &other) const {
  if(this->value==other.value){
      return true;
  }
  return false;
}

/*
* Some Method
*/
std::shared_ptr<Parent> someObject(new Child(3));
std::shared_ptr<Parent> anotherObject(new Child(4));
//!!!calls == operator for shared_ptr, but not for Child
if(someObject==anotherObject){
//do sth
}

我感谢这里的任何意见!谢谢。

最好

当静态已知类型Parent(确实如此)时,您需要为Parent定义一个operator==

拥有虚拟operator==存在问题,但是假设您在类Parent中有一些operator==,无论是否虚拟

,然后执行
std::shared_ptr<Parent> someObject(new Child(3));
std::shared_ptr<Parent> anotherObject(new Child(4));
//calls == operator for Parent
if( *someObject == *anotherObject){
//do sth
}

如果没有取消引用* s(或一些等效项),您只会比较shared_ptr实例,正如您所发现的那样。

正如 Alf 建议的那样,您需要更改 if 语句以比较对象本身而不是指针。

此外,如果存在需要特殊处理以确定它们是否相等的子类型,则operator==需要遵从虚函数以进行实际比较。

bool Parent::operator==(const Parent& other) const
{
    return equals(other);
}
bool Child::equals(const Parent& other) const
{
    Child * otherChild = dynamic_cast<Child*>(&other);
    if (otherChild != NULL)
        // compare child to child
    else
        // compare child to other type
}