我得到了一个带有纯虚方法的抽象基类“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
}
我很感激这里的任何输入!谢谢你。
最好的,