C++ == 运算符,用于使用 shared_ptr 的抽象基类的子级
C++ == operator for child of abstract base class using shared_ptr
我得到了一个抽象基类"Parent",其中包含一个纯虚拟方法和一个实现此方法的子类"Child"和一个成员"值"。我将子类的对象实例化为shared_ptr作为动态绑定的一种方式。我在这里使用shared_ptr而不是引用,因为我将这些对象存储在 std::vector 中。
现在我想比较源代码底部定义的两个对象"someObject"和"otherObject"。因此,我覆盖了相应 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
}
我感谢这里的任何意见!谢谢。
最好
当静态已知类型Parent
(确实如此)时,您需要为Parent
定义一个operator==
。
拥有虚拟operator==
存在问题,但是假设您在类Parent
中有一些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
}
相关文章:
- 无法创建抽象类的实例
- 如何定义一个纯抽象基类
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 用pybind11包装C++抽象类时出错
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 有没有办法按值将纯抽象类的所有子类传递给 C++ 中的函数?
- 抽象类错误,请参阅声明" "是抽象的
- 将自定义函数传递到基抽象类中以延迟执行
- 命名参数习惯用法和(抽象)基类
- 打印抽象对象 c++
- 如何在从抽象基派生的类中实现相同的方法?
- 将包含抽象类和普通类C++包导出到 Python
- C++:处理抽象类中的错误时出现问题
- 为共享 ptr 向量实现复制 c'tor?
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- C++抽象的字节序是中立的吗?
- 崩溃 __cxxabiv1::__cxa_pure_virtual () - vtable ptr 到抽象基类