C++中有没有一种惯用的方法来比较多态类型的对象等价性
Is there an idiomatic approach in C++ for comparing polymorphic types for object equivalence?
我有指向多态类型的两个实例的Base*指针,我需要确定引用的对象是否等效。
我目前的方法是首先使用RTTI来检查类型是否相等。如果类型相等,那么我调用一个虚拟is_equivalent函数。
有更惯用的方法吗?
对于大多数派生类,等价仅仅意味着成员变量都具有相同的值
在C++中,这被称为"相等",通常使用operator==()
来实现。在C++中,你可以覆盖运算符的含义,可以写:
MyType A;
MyType B;
if (A == B) {
// do stuff
}
并让==
调用您定义的自定义函数。
我想你想把相等和身份区分开来,身份意味着相同的对象(即相同的地址)。
您可以将其实现为成员函数或免费函数(来自维基百科):
bool T::operator ==(const T& b) const;
bool operator ==(const T& a, const T& b);
在您的情况下,您希望为基类实现operator==
,然后执行您正在执行的操作。
更具体地说,它看起来是这样的:
class MyBase
{
virtual ~MyBase(); // reminder on virtual destructor for RTTI
// ...
private:
virtual bool is_equal(const MyBase& other);
friend bool operator ==(const MyBase& a, const MyBase& b);
// ...
};
bool operator ==(const MyBase& a, const MyBase& b)
{
// RTTI check
if (typeid(a) != typeid(b))
return false;
// Invoke is_equal on derived types
return a.is_equal(b);
}
class D1 : MyBase
{
virtual bool is_equal(const Base& other)
{
const D1& other_derived = dynamic_cast<const D1&>(other);
// Now compare *this to other_derived
}
};
class D2 : MyBase;
{ };
D1 d1; D2 d2;
bool equal = d1 == d2; // will call your operator and return false since
// RTTI will say the types are different
相关文章:
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 比较两个节点坐标的最佳方法是什么?
- 比较C++中两个整数的最有效和最干净的方法是什么?
- 比较C++变量的最有效方法
- "operator()"在重载运算符方法中是什么意思,在priority_queue(STL)中用作C++中的比较器?
- 比较"A"、"C"、"G"'T'字符的最快方法
- 任何方法都可以在C++中比较数据结构中的许多方法
- 是否有任何统一的方法可以在 c++ 中创建自定义比较器?
- 在 c++ 中比较不相等数组或字符串的方法
- 使用 lambda 比较初始化优先级队列的方法
- C# 通用比较方法 [C++模板的类似物]
- 比较字符* (C/C++) 的最快方法?
- 获取字符串大小的各种方法之间的比较
- C 是否具有对两个STD :: sets,vectors等进行三角比较的标准方法
- 比较两个文件中的两个中间人的最佳方法.C++
- 两种数字比较方法中哪一种更有效
- C++标准::地图比较方法
- 为什么比较方法不起作用?
- 对于C++字符串最好使用比较方法或关系运算符
- 类中的比较方法