我的目标是允许链接方法,例如:
class Foo;
Foo f;
f.setX(12).setY(90);
Foo
的方法是否可以返回指向其实例的指针,允许这样的链接?
答案 0 :(得分:10)
对于该特定语法,您必须返回引用
class Foo {
public:
Foo& SetX(int x) {
/* whatever */
return *this;
}
Foo& SetY(int y) {
/* whatever */
return *this;
}
};
P.S。或者您可以返回副本(Foo
而不是Foo&
)。没有更多细节,没有办法说出你需要的东西,但是根据你在例子中使用的函数名称(Set...
)判断,你可能需要一个引用返回类型。
答案 1 :(得分:4)
另一个例子是Named Parameter Idiom。
答案 2 :(得分:3)
是的,可能。一个comon示例是运算符重载,例如operator + =()。
例如,如果您有一个名为ComplexNumber的类,并且想要执行诸如+ = b之类的操作,那么您可以
ComplexNumber& operator+=(ComplexNumber& other){
//add here
return *this;
}
在您的情况下,您可以使用。
Foo& setX(int x){
//yada yada yada
return *this;
}
答案 3 :(得分:2)
好吧,您可以从自己的函数返回对象,以便将函数链接在一起:
#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
答案 4 :(得分:0)
#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