古い日記に言及, メソッドチェーン
#include <iostream> class Foo { public: void method() { std::cout << "hello!\n"; } }; int main(int, char*[]) { new Foo()->method(); return 0; }
いやいや、C++でのメソッドチェーンとは次のような書き方をします。
class C { public: C(int n) : n(n) { } C methodA() { // 非constなメンバ関数A ++n; return *this; } C methodB() { // 非constなメンバ関数B n *= 2; return *this; } void show() const { // 表示する printf("n=%d\n", n); } private: int n; };
における、
C(10).methodA().methodB().show();
なにかとnewしないと行けないみたいな思い込みがあるのは変な解説が多すぎる(た)からですね。特にJavaからC++を勉強した人とかにありがち。newなんて使いませんから!!