2010-12-24 23 views
2

我想了解如何顯式構造函數調用主要使用下面的代碼工程。顯式使用main中的構造函數調用作爲函數調用參數

#include<iostream> 

using namespace std; 

class Dependency1 
{ 
     bool init; 
public: 
    Dependency1() : init(true) { 
    std::cout << "Dependency1 construction" 
       << std::endl; 
    } 
    void print() const { 
    std::cout << "Dependency1 init: " 
       << init << std::endl; 
    } 



}; 


class Dependency2 { 
    Dependency1 d1; 
public: 
    Dependency2(const Dependency1& dep1): d1(dep1){ 
    std::cout << "Dependency2 construction "; 
    print(); 
    } 
    void print() const { d1.print(); } 
}; 

void test(const Dependency1& dd1) 
{ 
    cout << " inside Test \n"; 
    dd1.print(); 
} 



int main() 
{ 

    test(Dependency1()); 
    Dependency2 D1(Dependency1()); // this line does not work 

    return 0; 
} 

功能測試正在被呼叫,其中構造依賴關係1()被用作一個函數調用,而不是依賴關係1 ::依賴關係1()和代碼運行完全正常。

現在,如果我用類似的概念創造Dependency2的對象D1,這是行不通的。 似乎我在這裏做錯了錯誤的理解。

需要知道編譯器如何解析依賴關係1()在主通話,即使不使用範圍解析和它爲什麼當我使用它作爲Dependency2

謝謝, 的構造函數的參數不工作阿南德

回答

1

依賴關係1()創建類型依賴關係1的臨時對象,被傳遞到功能測試。

+0

+1簡單易懂,易於理解。 – 2010-12-24 05:28:13

+0

謝謝,但是爲什麼當我使用類似的東西來創建Dependency2對象時它不起作用。 – Anand 2010-12-24 05:30:26

+0

@Anand:看看我的答案。 – 2010-12-24 05:40:10

7

test(Dependency1())

此調用一個函數test並傳遞Dependency1類的臨時對象。因爲在test定義的形式參數是const參考,因爲臨時對象可以綁定到const引用您的代碼工作。

Dependency2 D1(Dependency1()); // this line does not work

這就是所謂的C++最令人頭痛的解析。 D1被解釋爲函數返回Dependency2並採用參數指向函數返回Dependency1

嘗試Dependency2 D1((Dependency1()));,看到在輸出的變化。

注:把一對額外的括號將使編譯器治療(Dependency1())作爲一種表達。

+0

比我的更重要。 – Oswald 2010-12-24 05:34:04

+0

太好了。謝謝。有沒有其他方法可以讓編譯器將D1作爲對象而不是函數? – Anand 2010-12-24 05:51:50

+0

@Prasoon:+1這個完美的答案。好工作:-) – Nawaz 2010-12-24 05:52:01