【发布时间】:2011-07-20 18:27:13
【问题描述】:
基本上,我有一个名为 VisaMux 的类和一个名为 MuxPath 的类。 MuxPath 有一个 VisaMux 私有实例变量。我希望 MuxPath 的构造函数将实例变量分配给给定的 VisaMux 对象,而不调用空的 VisaMux() 构造函数。
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 行)出错,因此 const VisaMux& Mux 似乎以某种方式调用了不存在的 VisaMux()。如果我只使用 VisaMux Mux,也会发生这种情况。
我不希望它为 VisaMux 调用空构造函数,因为我希望仅通过向其构造函数传递所有必要参数来创建 VisaMux。
我该怎么做?
【问题讨论】:
-
答案如下,告诉你使用初始化列表语法。我只想补充一点,您应该更喜欢使用初始化语法,否则您经常在参数列表中构造对象两次。默认情况下一次,然后在构造函数的主体内一次。此外,您应该按照声明它们的顺序将项目放入初始化列表中(参见 S. Meyers Effective C++ item 13)
-
@Andrew Wiens:看看这个答案here 解释了成员初始化和构造函数体内赋值之间的区别
标签: c++ constructor