2016-08-01 58 views
4

我一直在研究由其他人(誰離開公司)啓動的C++項目。他寫了一段代碼,似乎工作得很好,但我無法理解它。C++ 11 /生成的構造函數

這裏是下面的代碼的簡化版本:

有兩類:

class Algo_t { 
protected : 
    Matrix_t m_Matrix ; 
public: 
    Algo_t(Matrix_t && Matrix) { 
     DoSomething(); 
    } 
}; 

class Matrix_t { 
protected : 
    std::ifstream & m_iftsream ; 
public: 
    Matrix_t(std::ifstream && ifstream) { 
     DoSomething(); 
    } 
}; 

在主:

有在主函數下面的調用:

char * pMyFileName = agrv[1] ; 
Algo_t MyAlgo(ifstream(pMyFileName)); 

首先,我非常驚訝的是,代碼編譯沒有任何錯誤becau se沒有構造函數Algo_tifstream作爲參數。 我更驚訝地發現這個代碼工作得很好。

構造函數是由編譯器生成還是由C++ 11引入了一些新特性(使用右值...)?

+1

也許類'Matrix_t'有一個'ifstream'鑄造運營商,或需要'ifstream'的構造函數?哦,嘿,它確實...這就解釋了它...... –

+0

即使修復了一些明顯的錯誤,您的簡化版本也不會編譯。 –

+1

這與你構造一個帶'const char []'的'std :: string'的結構(幾乎) 'std :: stringstream(「Hello World!」)' - 你不需要顯式地執行'std :: stringstream(std :: string(「Hello World!」))''。 – Holt

回答

8

在C++中,最多允許一個用戶定義的轉換。您無法直接從ifstream構建Algo_t,但可以使用ifstream構建Matrix_t。因此,在

Algo_t MyAlgo(ifstream(pMyFileName)); 

編譯器構建一個臨時Matrix_t(您的一個用戶定義的轉換),然後您使用臨時構建MyAlgo

+0

最多一個?如果我們嘗試使用更多,會發生什麼? – CinCout

+1

@CinCout代碼格式不正確。 – Holt

+0

@CinCout它不起作用。假設你有另外一個類'Foo',可以用'Algo_t'構造。 'Foo MyFoo(ifstream(pMyFileName));'不起作用。 – NathanOliver

3

您的矩陣構造函數被隱式調用,因爲它需要ifstream&&。如果你把它明確的,它不會工作:

explicit Matrix_t(std::ifstream && ifstream) { 
    DoSomething(); 
} 
4

至於解釋here

單參數的構造函數:允許來自 特定類型的隱式轉換初始化對象。

因此,存在因構造的隱式轉換選項從ifstreamMatrix_t

Matrix_t(std::ifstream && ifstream) 

所以當你叫:

Algo_t MyAlgo(ifstream(pMyFileName)); 

ifstream(pMyFileName)對象轉換爲Matrix_t對象,然後由施工人員使用Algo_t(Matrix_t && Matrix)