我打算写一个这样的 multimap
std::multimap <key, base_ptr> mymap;
而且我希望能够存储从基类派生的许多派生类(例如 Der1
、Der2
)的指针。
现在,当我试图将一个对象插入到映射中时,我首先在键上进行查找,然后我需要比较该对象是否是 EQUIVALENT(不必是同一个对象,因此不进行指针比较) 到那个位置的那个。因此,假设我重写了 == operator
或编写了某种比较函数。现在我想为此编写代码,这样当添加新的派生类时,我不必更改或添加任何内容。
所以我认为必须有一种通用的编写方法。但想不出一个。
我在想下面这样的事情
class Base
{
virtual Base * get() { return this; }
virtual bool isEqual(const Base& toObj) {
....
}
}
class Der1
{
Der1 * get() { return this; }
bool isEqual(const Der1& toObj) {
....
}
}
但这似乎也行不通。因为当我这样做时:
Base* bp1;
Base* bp2;
bp1->get()->isEqual(*(bp2->get()))
我看到对 get()
的调用确实像我预期的那样在派生类的 get()
中结束,但随后编译器会处理返回值作为 Base*
。这很可能是因为它是运行时多态性。但我很难相信不会有一种优雅而明显的方法来做到这一点。
有人可以建议吗。
最佳答案
你可以尝试这样的事情:
class Base
{
public:
// derived classes must implement this.
// the implementation is always the same code
virtual type_info getType() const = 0;
virtual bool isEqual(const Base& toObj) = 0;
}
class Der1 : Base
{
public:
type_info getType() const { return typeid (this); }
bool isEqual(const Base& toObj)
{
if (this.getType() == toObj.getType())
{
// we have 2 instances of Der1!
// do comparison here
}
else
{
// the other one is no Der1 => we are not equal
return false;
}
}
}
class Der2 : Base
{
public:
type_info getType() const { return typeid (this); }
bool isEqual(const Base& toObj)
{
if (this.getType() == toObj.getType())
{
// we have 2 instances of Der2!
// do comparison here
}
else
{
// the other one is no Der1 => we are not equal
return false;
}
}
}
void MyFunc()
{
Base* bp1;
Base* bp2;
// ...
// this should work now (although I have not tested it!)
bool theyAreEqual = bp1->isEqual(*bp2);
}
关于c++ - 在 C++ 中一般比较继承层次结构中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21529062/