假设我有一个类型层次结构:
struct B { ... };
struct D1 : B { ... };
struct D2 : B { ... };
...
struct Dn : B { ... };
Run Code Online (Sandbox Code Playgroud)
每个Di都有自己的operator==定义:
struct Di : B
{
bool operator==(const Di&) const { ... }
...
};
Run Code Online (Sandbox Code Playgroud)
我现在想要定义B,operator==这样:
struct B
{
bool operator==(const B& that) const
{
// psuedo-code
let i, such the dynamic type of this is Di
let j, such the dynamic type of that is Dj
if (i != j)
return false;
else
return Di::operator==(this, that);
}
}
Run Code Online (Sandbox Code Playgroud)
组织这个或写这个的最好方法是什么?
(最终目标是我想使用值类型为B*的标准容器类型(例如std::set<B*>),但是Di::operator==s当它们来自同一派生类时使用自定义)
在基类中定义受保护的虚函数.使其成为纯虚拟,以确保每个子类Di提供实现.该函数将知道强制转换的目标,因为它属于a Di.从==基类中的运算符调用该函数,并让它执行比较,如下所示:
struct B {
bool operator==(const B& that) const {
return this->equals(that);
}
protected:
virtual bool equals(const B& other) const=0;
};
struct D1 {
protected:
virtual bool equals(const B& other) const {
D1 *that = dynamic_cast<D1*>(&other);
if (!that) return false;
// Perform D1-specific comparison here.
// You can use the == operator of D1, but you do not have to:
return (*this) == (*that);
}
};
Run Code Online (Sandbox Code Playgroud)
这种结构的作用是使==操作符虚拟的实现.
| 归档时间: |
|
| 查看次数: |
290 次 |
| 最近记录: |