C++ 结构体构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19743115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ struct constructor
提问by PepeHands
I tried to create my own structure. So I wrote this piece of code.
我试图创建自己的结构。所以我写了这段代码。
struct node
{
int val, id;
node(int init_val, int init_id)
{
val = init_val;
id = init_id;
}
};
node t[100];
int main()
{
...
}
I tried to compile my program. But I got an error:
我试图编译我的程序。但我得到了一个错误:
error: no matching function for call to 'node::node()'
note: candidates are:
note: node::node(int, int)
note: candidate expects 2 arguments, 0 provided
note: node::node(const node&)
note: candidate expects 1 argument, 0 provided
回答by simonc
node t[100];
will try to initialise the array by calling a default constructor for node
. You could either provide a default constructor
将尝试通过为 调用默认构造函数来初始化数组node
。您可以提供默认构造函数
node()
{
val = 0;
id = 0;
}
or, rather verbosely, initialise all 100 elements explicitly
或者,更详细地说,显式初始化所有 100 个元素
node t[100] = {{0,0}, {2,5}, ...}; // repeat for 100 elements
or, since you're using C++, use std::vector
instead, appending to it (using push_back
) at runtime
或者,由于您使用的是 C++,请std::vector
改为使用,push_back
在运行时附加到它(使用)
std::vector<node> t;
回答by iDebD_gh
This will fix your error.
这将修复您的错误。
struct node
{
int val, id;
node(){};
node(int init_val, int init_id)
{
val = init_val;
id = init_id;
}
};
You should declare default constructor.
您应该声明默认构造函数。