C++ 上的虚拟等号函数
我正在尝试做类似的事情:
class A
{
public:
A() = default;
~A() = default;
public:
bool operator==(const A& a)
{
return this->equal(a);
};
private:
virtual bool equal(const A& other) const = 0;
};
class B : public A
{
public:
B() = default;
~B() = default;
private:
virtual bool equal(const A& other) const override
{
const B* b = dynamic_cast<const B*>(&other);
if (!b)
return false;
return m_example == b->m_example;
}
private:
double m_example; //This is just an example data I don't need specific solution for double :)
};
目标:只有相同类型的类别= B的类别
- 。
- 是否有标准解决方案可以具有虚拟平等运算符?
- 我会从很多(4/8类)中吸入,我该如何干净地进行检查,检查指针是否非常丑陋。
请你帮助我好吗?
I am trying to do something like:
class A
{
public:
A() = default;
~A() = default;
public:
bool operator==(const A& a)
{
return this->equal(a);
};
private:
virtual bool equal(const A& other) const = 0;
};
class B : public A
{
public:
B() = default;
~B() = default;
private:
virtual bool equal(const A& other) const override
{
const B* b = dynamic_cast<const B*>(&other);
if (!b)
return false;
return m_example == b->m_example;
}
private:
double m_example; //This is just an example data I don't need specific solution for double :)
};
Goal: Only equality possible is between classes of same type = B.
- Is that ok?
- Is there a standard solution to have a virtual equal operator?
- I will be inherting from A a lot (4/8 classes), how can I do this in a clean way, the check if the pointer is null looks very ugly.
Could you please help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个观点,即动态演员是否丑陋,还是不丑陋。这是一个无尽的辩论,但这没关系。那是因为这里不需要动态演员。可以使用继承干净地完成:
It's a matter of opinion whether dynamic casts are ugly, or not. It's an endless debate, but it doesn't matter here. That's because dynamic casts are not needed here. This can be done, cleanly, using inheritance: