C++ 中是否有一种惯用的方法来比较对象等价的多态类型?
我有指向多态类型的两个实例的 Base* 指针,我需要确定引用的对象是否等价.
I have Base* pointers to two instances of a polymorphic type and I need to determine if the referenced objects are equivalent.
我目前的方法是首先使用 RTTI 来检查类型是否相等.如果类型相等,则调用虚拟 is_equivalent 函数.
My current approach is to first use RTTI to check for type equality. If the types are equal, I then call a virtual is_equivalent function.
还有更惯用的方法吗?
推荐答案
对于大多数派生类来说,等价只是意味着成员变量的值都相同
For most of the derived classes, equivalent simply means that the member variables all the same value
在 C++ 中,这称为平等",通常使用 operator==()
实现.在C++中你可以重写操作符的含义,可以这样写:
In C++ this is called 'equality' and is usually implemented using operator==()
. In C++ you can override the meaning of operators, it is possible to write:
MyType A;
MyType B;
if (A == B) {
// do stuff
}
并让 ==
调用您定义的自定义函数.
And have ==
call a custom function you define.
我认为您想将平等与身份区分开来,这意味着相同的对象(即相同的地址).
I think you want to differentiate equality from identity which would mean the same object (i.e. same address).
您可以将其实现为成员函数或自由函数(来自维基百科):
You can implement it as member function or free function (from wikipedia):
bool T::operator ==(const T& b) const;
bool operator ==(const T& a, const T& b);
在您的情况下,您想为基类实现 operator==
,然后执行您正在执行的操作.
In your case you want to implement operator==
for the base class, and then perform what you are doing.
更具体地说,它看起来像这样:
More concretely it would look like this:
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
相关文章