¿Puedes encadenar métodos devolviendo un puntero a su objeto?
-
06-07-2019 - |
Pregunta
Mi objetivo es permitir el encadenamiento de métodos como:
class Foo;
Foo f;
f.setX(12).setY(90);
¿Es posible que los métodos de Foo
devuelvan un puntero a su instancia, permitiendo dicho encadenamiento?
Solución
Para esa sintaxis específica, tendrías que devolver una referencia
class Foo {
public:
Foo& SetX(int x) {
/* whatever */
return *this;
}
Foo& SetY(int y) {
/* whatever */
return *this;
}
};
P.S. O puede devolver una copia ( Foo
en lugar de Foo & amp;
). No hay forma de decir lo que necesita sin más detalles, pero a juzgar por el nombre de la función ( Set ...
) que utilizó en su ejemplo, probablemente necesite un tipo de retorno de referencia.
Otros consejos
Otro ejemplo es el Idioma de parámetro con nombre .
Sí, es posible. Un ejemplo común es la sobrecarga del operador, como el operador + = ().
Por ejemplo, si tiene una clase llamada ComplexNumber y desea hacer algo como a + = b, entonces podría
ComplexNumber& operator+=(ComplexNumber& other){
//add here
return *this;
}
En tu caso podrías usar.
Foo& setX(int x){
//yada yada yada
return *this;
}
Bueno, puedes devolver un objeto desde su propia función para encadenar funciones:
#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;
}
Qué resultados:
$ ./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;
}
Salida:
Hello
Goodbye