簡體   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