代码之家  ›  专栏  ›  技术社区  ›  sivabudh

调用基类方法的简洁(但仍具有表现力)C++语法

  •  4
  • sivabudh  · 技术社区  · 15 年前

    我想特别调用基类方法;最简洁的方法是什么?例如:

    class Base
    {
    public:
      bool operator != (Base&);
    };
    
    class Child : public Base
    {
    public:
      bool operator != (Child& child_)
      {
        if(Base::operator!=(child_))  // Is there a more concise syntax than this?
          return true;
    
        // ... Some other comparisons that Base does not know about ...
    
        return false;
      }
    };
    
    5 回复  |  直到 15 年前
        1
  •  8
  •   Andrew Stein    15 年前

    不,尽可能简洁。 Base::operator!= 是方法的名称。

    是的,你所做的是标准的。

    但是,在您的示例中(除非您删除了一些代码),您不需要 Child::operator!= 完全。它的作用和 基地:接线员!= 威尔。

        2
  •  5
  •   Alexey Malistov    15 年前

    if ( *((Base*)this) != child_ ) return true;
    

    if ( *(static_cast<Base*>(this)) != child_ ) return true;
    

    class Base  
    {  
    public:  
      bool operator != (Base&);  
      Base       & getBase()       { return *this;}
      Base const & getBase() const { return *this;}
    }; 
    
    if ( getBase() != child_ ) return true;
    
        3
  •  3
  •   Community Mohan Dere    8 年前

    你所做的是最简洁和“标准”的方式,但有些人更喜欢这样:

    class SomeBase
    {
    public:
        bool operator!=(const SomeBaseClass& other);
    };
    
    class SomeObject: public SomeBase
    {
        typedef SomeBase base;  // Define alias for base class
    
    public:
        bool operator!=(const SomeObject &other)
        {
            // Use alias
            if (base::operator!=(other))
                return true;
    
            // ...
    
            return false;
        }
    };
    

    这个方法的好处是它澄清了意图,它给你一个标准的缩写,可以是一个很长的基类名称,如果你的基类改变了,你不必改变基类的每次使用。

    Using "super" in C++ 以供进一步讨论。

    (就我个人而言,我不在乎这个,也不推荐,但我认为这是对这个问题的一个有效答案。)

        4
  •  1
  •   fredoverflow    15 年前
    if (condition) return true;
    return false;
    

    可以缩写为

    return condition;
    
        5
  •  -1
  •   Dathan    15 年前

    我会去掉if/then控件结构,只返回基类运算符的返回值,否则您所做的就可以了。

    它可以更简洁一点,不过: return ((Base&)*this) != child_;

    推荐文章