1

我得到了一个带有纯虚方法的抽象基类“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
}

我很感激这里的任何输入!谢谢你。

最好的,

4

2 回答 2

5

当静态已知类型是Parent(并且确实是)时,您需要operator==Parent.

有一个 virtual 有问题operator==,但假设你有一些operator==,无论是否虚拟,在 class 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
}

正如您发现的那样,如果没有取消引用*s (或其他等价物),您只会比较shared_ptr实例。

于 2012-12-17T18:42:07.240 回答
2

正如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
}
于 2012-12-17T18:50:33.853 回答