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++での「スーパー」の使用を参照してください。

(個人的には、これは気にしないので、お勧めしませんが、質問に対する有効な答えの1つだと思います。)

于 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 に答える