基本上,我有一個名爲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只能通過構造函數傳遞所有必要的參數來創建。
我該怎麼做?
答案在下面,並告訴你使用初始化列表語法。我只想補充一點,你應該更喜歡使用初始化語法,否則你經常在你的參數列表中兩次構造對象。默認一次,一次在構造函數的內部。你也應該按照你聲明的順序把它們放到你的初始化列表中(參見S. Meyers Effective C++ item 13) – Tod
@Andrew Wiens:看看這個答案[here](http://stackoverflow.com/ questions/6724626/c-constructor/6724639#6724639)解釋了構造函數體內成員初始化和賦值的區別 –