オブジェクトへのポインタを返すことでメソッドを連鎖できますか?

StackOverflow https://stackoverflow.com/questions/1619831

  •  06-07-2019
  •  | 
  •  

質問

私の目標は、次のようなメソッドのチェーンを許可することです

class Foo;
Foo f;
f.setX(12).setY(90);

Foo のメソッドがインスタンスへのポインタを返し、そのような連鎖を許可することは可能ですか?

役に立ちましたか?

解決

その特定の構文については、参照を返す必要があります

class Foo {
public:

  Foo& SetX(int x) {
    /* whatever */
    return *this;
  } 

  Foo& SetY(int y) {
    /* whatever */
    return *this;
  } 
};

PSまたは、コピーを返すことができます( Foo& の代わりに Foo )。詳細なしに必要なものを言う方法はありませんが、例で使用した関数名( Set ... )から判断すると、おそらく参照戻り型が必要です。

他のヒント

はい、可能です。 comonの例は、operator + =()などの演算子のオーバーロードです。

たとえば、ComplexNumberというクラスがあり、a + = bなどの処理を実行したい場合、

ComplexNumber& operator+=(ComplexNumber& other){
     //add here
     return *this; 
}

あなたの場合は使用できます。

Foo& setX(int x){
//yada yada yada
return *this;
}

まあ、関数を連鎖させるために、独自の関数からオブジェクトを返すことができます:

#include <iostream>
class foo
{
    public:
        foo() {num = 0;}
        // Returning a `foo` creates a new copy of the object each time...
        // So returning a `foo&` returns a *reference* to this, and operates on
        // the *same* object each time.
        foo& Add(int n)  
        {
            num += n;
            std::cout << num << std::endl;
            // If you actually DO need a pointer, 
            // change the return type and do not dereference `this`
            return *this;  
        }
    private:
        int num;
};

int main()
{
    foo f;
    f.Add(10).Add(5).Add(3);
    return 0;
}

出力:

$ ./a.out
10
15
18
#include <iostream>

using namespace::std;

class Print
{
    public:
        Print * hello();
        Print * goodbye();
        Print * newLine();
};

Print * Print::hello()
{
    cout << "Hello";
    return this;
}
Print * Print::goodbye()
{
    cout << "Goodbye";
    return this;
}
Print * Print::newLine()
{
    cout << endl;
    return this;
}

int main (void)
{
    Print print;
    print.hello()->newLine()->goodbye()->newLine();

    return 0;
}

出力:

   Hello
   Goodbye
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top