1

純粋仮想メソッドを持つ抽象基本クラス「親」と、このメソッドとメンバー「値」を実装する子クラス「子」を取得しました。動的バインディングの手段として、子クラスのオブジェクトを shared_ptr としてインスタンス化します。これらのオブジェクトを std::vector に格納するため、ここでは参照の代わりに shared_ptr を使用します。

ここで、ソース コードの下部に定義されている 2 つのオブジェクト "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

静的に知られている型が(そしてそうである) 場合、 for を定義Parentする必要があります。operator==Parent

virtual を持つことには問題がありますが、 virtual であろうとなかろうと、 classに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
}

あなたが発見したように、間接参照*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 に答える