2011-07-20 46 views
2

基本上,我有一個名爲VisaMux的類和一個名爲MuxPath的類。 MuxPath有一個VisaMux專用實例變量。我希望MuxPath的構造函數可以爲給定的VisaMux對象分配實例變量,而無需調用空的VisaMux()構造函數。如何在不調用C++中的構造函數的情況下分配實例變量?

5 MuxPath::MuxPath(const uint& Clk_sel, const uint& Lane_sel, const VisaMux& Mux){ 
6  clk_sel = Clk_sel; 
7  lane_sel = Lane_sel; 
8  mux = Mux; 
9 } 

此代碼導致錯誤:

MuxPath.cpp:5: error: no matching function for call to ‘VisaMux::VisaMux()’ 
VisaMux.h:20: candidates are: VisaMux::VisaMux(const std::string&, const uint&, const uint&, const std::vector<VisaLane, std::allocator<VisaLane> >&, const std::vector<VisaResource, std::allocator<VisaResource> >&) 

正如你可以看到,它的第一線(5號線)的錯誤,如此看來,不知怎的,常量VisaMux &複用器被調用VisaMux( ),這不存在。如果我只是使用VisaMux Mux,也會發生這種情況。

我不想讓它爲VisaMux調用一個空的構造函數,因爲我希望VisaMux只能通過構造函數傳遞所有必要的參數來創建。

我該怎麼做?

+0

答案在下面,並告訴你使用初始化列表語法。我只想補充一點,你應該更喜歡使用初始化語法,否則你經常在你的參數列表中兩次構造對象。默認一次,一次在構造函數的內部。你也應該按照你聲明的順序把它們放到你的初始化列表中(參見S. Meyers Effective C++ item 13) – Tod

+0

@Andrew Wiens:看看這個答案[here](http://stackoverflow.com/ questions/6724626/c-constructor/6724639#6724639)解釋了構造函數體內成員初始化和賦值的區別 –

回答

6

使用構造函數初始化列表:

MuxPath::MuxPath(const uint& Clk_sel, const uint& Lane_sel, const VisaMux& Mux) 
     : clk_sel(Clk_sel) 
     , lane_sel(Lane_sel) 
     , mux(Mux) 
{} 
0
MuxPath::MuxPath(const uint& Clk_sel, const uint& Lane_sel, const VisaMux& Mux) 
     : mux(Mux) 
    { 
     clk_sel = Clk_sel; 
     lane_sel = Lane_sel; 
    } 

它被稱爲「初始化列表」。

0
class MuxPath { 
    MuxPath(const uint& Clk_sel, const uint& Lane_sel, const VisaMux& Mux) 
    : clk_sel(Clk_sel), lane_sel(Lane_sel), mux(Mux) {}; 
    ... 
}; 
5

使用成員初始化列表在構造函數爲:

MuxPath::MuxPath(const uint& Clk_sel, const uint& Lane_sel, const VisaMux& Mux) 
    :clk_sel (Clk_sel),lane_sel(Lane_sel),mux(Mux) 
{ //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it's called initialization-list 

} 

其實,在你的代碼,所有的成員變量使用分配而不是各自構造,這意味着mux嘗試使用默認構造函數構建,甚至在它進入構造函數之前。並且由於VisaMux沒有默認構造函數,因此給出了編譯錯誤。

因此,通過使用初始化列表(其中語法mux(Mux)調用VisaMux的複製構造函數),可以避免調用VisaMux不存在的默認構造函數。由於mux已經複製構建,所以在構造函數體中不需要使用賦值

0

你有種詢問如何,你可以在你的房子得到紅牆不首先安裝牆上釘。如果您的類包含Mux變量,則在其構建過程中的某個時刻,將需要實例化Mux類型的變量。這意味着將創建一個Mux類型的實例,唯一的機制是使用構造函數調用。

這可以是默認值,也可以是無參數構造函數,複製構造函數或接受其他參數的構造函數。其他答案顯示瞭如何在成員初始化列表中執行此操作。但是沒有辦法解決這個事實,在某些時候,Mux的一些構造器需要被調用。

相關問題