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

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;
  }
};
有帮助吗?

解决方案

不,那很简洁。 Base::operator!= 是该方法的名称。

是的,您正在做的是标准配置。

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

其他提示

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;

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

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 ++中使用“超级” 进行其他讨论。

(就我个人而言,我不在乎,我不建议这样做,但我认为这是对问题的有效答案。)

if (condition) return true;
return false;

可以缩写为

return condition;

我会摆脱if/then控制结构,然后返回基类操作员的返回值,但否则您的工作还不错。

但是,它可能会更简洁: return ((Base&)*this) != child_;

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top