C++ ==使用shared_ptr的抽象基类的子操作符

Chr*_*ris 1 c++ dynamic shared-ptr

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

现在我想比较源代码底部定义的两个对象"someObject"和"anotherObject".因此,我在相应的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
}
Run Code Online (Sandbox Code Playgroud)

我感谢这里的任何输入!谢谢.

最好,

Che*_*Alf 5

当静态已知类型是Parent(并且是)时,您需要为其operator==定义Parent.

有一个虚拟的问题operator==,但假设你有一些operator==,虚拟或没有,在课堂上Parent,然后做

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
}
Run Code Online (Sandbox Code Playgroud)

如果没有解除引用*(或某些等价物),您只需比较shared_ptr实例,就像您发现的那样.