[英]How do you use the non-default constructor for a member?
我有两节课
class a {
public:
a(int i);
};
class b {
public:
b(); //Gives me an error here, because it tries to find constructor a::a()
a aInstance;
}
如何获得它以便使用a(int i)
实例化aInstance
而不是尝试搜索默认构造函数? 基本上,我想从b
的构造函数中控制a
的构造函数的调用。
您需要在构造函数初始值设定项列表中显式调用 a(int) :
b() : aInstance(3) {}
其中 3 是您要使用的初始值。 虽然它可以是任何整数。 有关订单的重要说明和其他注意事项,请参阅评论。
使用初始化列表:
b::b() : aInstance(1) {}
只需使用一个定义如下的构造函数:
class b {
public:
b()
: aInstance(5)
{}
a aInstance;
};
前两个答案不起作用。 您将类声明放在 .h 头文件中,并将(成员)函数定义放在 .cpp 文件中。 受访者放置的大括号 {} 定义了 b 构造函数块。 在实践中,没有人会想要那个空的。 但是你不能在 .cpp 中正确定义它,否则编译器会报告 'redefinition' 错误。 (如果头文件在多个翻译单元中#included,链接器无论如何都会这样做)由于头文件的目的是它们可以包含在多个 .cpp 中,因此上述答案是不可行的。
我认为您应该使用指向“a”的指针,例如:
class b {
public:
b() : aInstance(new a(5)) {}
a *aInstance;
};
这样你就定义了行为。 当然,您需要在析构函数中释放 *aInstance。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.