如何为成员使用非默认构造函数?
我有两个类,
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
的构造函数的调用。
I have two classes
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;
}
How can I get it so that aInstance
is instantiated with a(int i)
instead of trying to search for a default constructor? Basically, I want to control the calling of a
's constructor from within b
's constructor.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要在构造函数初始值设定项列表中显式调用 a(int):
其中 3 是您要使用的初始值。虽然它可以是任何整数。有关订单的重要说明和其他注意事项,请参阅评论。
You need to call a(int) explicitly in the constructor initializer list:
Where 3 is the initial value you'd like to use. Though it could be any int. See comments for important notes on order and other caveats.
使用初始化列表:
Use an initialization list:
只需使用如下定义的构造函数:
Just use a constructor which is defined like this:
前两个答案不起作用。您将类声明放在 .h 头文件中,将(成员)函数定义放在 .cpp 文件中。受访者放置的大括号 {} 定义了 b 构造函数块。实际上,没有人会希望它是空的。但你不能在.cpp中正确定义它,否则编译器会报告“重新定义”错误。 (如果头文件 #included 在多个翻译单元中,链接器无论如何都会这样做)由于头文件的目的是它们可以包含在多个 .cpp 中,所以上面的答案是不可行的。
The top two answers won't work. You put class declarations in the .h header files, and (member) function definitions in the .cpp files. The braces {} that the respondents have put define the b constructor block. In practice no one would want that empty. Yet you can't define it properly in the .cpp or the compiler will report error of 'redefinition'. (As the linker would anyway if the header file is #included in several translation units) Since the purpose of header files is that they CAN be included in several .cpp's the answers above are unfeasable.
我认为你应该使用指向“a”的指针,例如:
这样你就可以定义行为。当然,您需要在析构函数中释放 *aInstance。
I think you should use a pointer to 'a' like:
This way you will have defined behaviour. Of course you will need to free *aInstance in the destructor.