是动态类型转换还是功能超载? [英] Dynamic Casts or Function Overloads?

查看:77
本文介绍了是动态类型转换还是功能超载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下抽象类:

class Abstract {
public:
    // ...

    virtual bool operator==(const Abstract& rhs) const = 0;

    // ...
};

现在假设我正在从该抽象类中创建多个派生类。但是,当与自己的类型进行比较时,每个算法都使用不同的算法,而与任何其他派生类进行比较时,则使用通用算法。在以下两个选项之间,哪个是更好,更有效的选项?

Now suppose I'm creating multiple derived classes from this abstract class. However, each one uses a different algorithm when comparing with its own type, and a generic algorithm when comparing with any of the other derived classes. Between the following two options, which would be the better, more efficient option?

选项A:

class Derived : public Abstract {
public:
    // ...

    bool operator==(const Abstract& rhs) const {
        // Code for comparing to any of the other derived classes
    }

    bool operator==(const Derived& rhs) const {
        // Code for comparing to myself
    }

    // ...
};

选项B:

class Derived : public Abstract {
public:
    // ...

    bool operator==(const Abstract& rhs) const {
        const Derived* tmp = dynamic_cast<const Derived*>(&rhs);
        if (tmp) {
            // Code for comparing to myself
        }
        else {
            // Code for comparing to any of the other derived class
        }
    }
};

我真的很好奇这些选项的优点和缺点,因为C ++类型转换是一种对我来说比较神秘的话题。此外,哪种解决方案更标准,第二种解决方案是否会对性能产生影响?

I'm really curious as to what advantages and disadvantages these options would have, as C++ typecasting is a relatively mysterious topic to me. Furthermore, which solution is more "standard", and does the second solution have any impacts on performance?

是否有第三种解决方案?尤其是如果有很多派生类,每个派生类需要针对不同派生类的特殊比较算法?

Is there possibly a third solution? Especially if there were many derived classes, each needing its own special comparison algorithm against different derived classes?

推荐答案

我认为选项B如果期望==运算符使用参数的动态类型,那么这就是您要查找的内容。例如:

I think that option B is what you are looking for if you're expecting the == operator to use the dynamic type of the argument. For example:

class base
{
public:
  virtual bool operator ==( const base& other ) = 0;
};

class derived : public base
{
public:
  bool operator ==( const base& other ) { return false; }
  bool operator ==( const derived& other ) { return true; }
};


int main()
{
  base* a = new derived;
  base* b = new derived;
  std::cout << ( *a == *b ) << std::endl;
}

此打印:

0

所以运算符==(const base & other),即使实际的动态类型是派生的

So operator ==( const base& other ) gets called, even if the actual dynamic type is derived.

这篇关于是动态类型转换还是功能超载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆