首先,我不是在談論C++ 11構造函數鏈構造函數代理。鏈調用成員函數關閉一個命名對象的構造函數
類成員函數可以返回對自身(類)的引用,因此可以鏈接函數調用。 (例如,運營商如何工作以允許連鎖呼叫。)
當實例化一個匿名對象時,此類鏈調用可能發生在構造函數外。
鏈調用可以從命名對象的構造函數創建嗎?下面的「foo a」和「foo b」的行不能編譯,所以我想知道是否有不同的語法。
#include <iostream>
using namespace std;
class foo {
public:
foo(int x) : val{x} { };
foo& inc() { ++val; return *this; }
int getVal() { return val; };
private:
int val;
};
int main() {
cout << foo(1).inc().getVal() << endl; // prints 2
cout << foo{2}.inc().inc().inc().inc().getVal() << endl; // prints 6
foo a(3).inc(); // error: expected ‘,’ or ‘;’ before ‘.’ token
foo b{4}.inc(); // error: expected ‘,’ or ‘;’ before ‘.’ token
cout << a.getVal() << endl;
cout << b.getVal() << endl;
}
基本上都是「不」。 'foo(1)'是一個表達式,'foo a(3)'不是一個表達式。你必須寫'foo a(3); a.inc();' –