# method chain 方法鏈 last update 2024/11/22 [C++方法链式调用_c++链式调用-CSDN博客](https://blog.csdn.net/weixin_39126199/article/details/130621048) recall:copy assigment operator method chain(chaining call) 跟 chaining assigment的概念相同,原因是他們都是return呼叫該方法/運算子的物件的引用(\*this)或是pointer。 區別在於用法: 1. 方法鏈 : 同一個物件鏈式呼叫不同的方法 chaining call ```cpp= obj.Method1().Method2().Method3(); ``` 2. chaining assigment : (同一個class/type的)不同物件各自呼叫同一個operator ```cpp= MyClass obj1, obj2, obj3; obj1 = obj2 = obj3; ``` ## reference :::spoiler reference ```cpp= #include <iostream> class MyClass { public: MyClass& Method1() { std::cout << "Method1 is called" << std::endl; return *this; } MyClass& Method2() { std::cout << "Method2 is called" << std::endl; return *this; } MyClass& Method3() { std::cout << "Method3 is called" << std::endl; return *this; } }; int main() { MyClass obj; obj.Method1().Method2().Method3(); return 0; } ``` ::: ## pointer ::: spoiler pointer ```cpp= #include <iostream> class MyClass { public: MyClass* Method1() { std::cout << "Method1 is called" << std::endl; return this; } MyClass* Method2() { std::cout << "Method2 is called" << std::endl; return this; } MyClass* Method3() { std::cout << "Method3 is called" << std::endl; return this; } }; int main() { MyClass* obj = new MyClass; obj->Method1()->Method2()->Method3(); delete obj; return 0; } ``` :::