5

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

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;
  }
};
4

5 回答 5

8

不,这是最简洁的。Base::operator!=是方法的名称。

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

但是,在您的示例中(除非您删除了一些代码),您根本不需要Child::operator!=。它和意志做同样的事情Base::operator!=

于 2010-03-12T17:42:08.903 回答
5

1

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

2

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

3

class Base  
{  
public:  
  bool operator != (Base&);  
  Base       & getBase()       { return *this;}
  Base const & getBase() const { return *this;}
}; 

if ( getBase() != child_ ) return true;
于 2010-03-12T17:45:36.067 回答
4

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

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;
    }
};

这种方法的好处是它明确了意图,它为可能是长基类名称的内容提供了标准缩写,并且如果您的基类发生更改,您不必更改基类的每次使用。

有关更多讨论,请参阅在 C++ 中使用“super” 。

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

于 2010-03-12T18:01:58.693 回答
0
if (condition) return true;
return false;

可以简写为

return condition;
于 2010-03-12T17:50:00.683 回答
-2

我会摆脱 if/then 控制结构,只返回基类运算符的返回值,但除此之外你所做的一切都很好。

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

于 2010-03-12T17:54:38.813 回答