繁体   English   中英

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

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

我得到了带有纯虚拟方法的抽象基类“ Parent”,以及实现该方法的子类“ Child”和成员“ value”。 我将子类的对象实例化为shared_ptr,以进行动态绑定。 我在这里使用了shared_ptr而不是引用,因为我将这些对象存储在std :: vector中。

现在,我想比较源代码底部定义的两个对象“ someObject”和“ anotherObject”。 因此,我已经覆盖了相应的Child类中的== operator。 但是,仅会调用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==

使用virtual operator==存在问题,但是假设您在Parent类中有一些virtual 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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM