C++可以初始化结构的动态阵列
struct article {
int uId;
char uName[201];
article(int Id, char* name) { uId = Id;
for(int i=0;name[i]!='\0';i++)
{
uName[i]=name[i];
}
}
};
int main()
{
char Name[201];
int ID;
int N;
cin>>N;
article* articleArr = new article[N]; //error thrown on this line
/*Some code that creates ID and Name*/
articleArr[index] = article(Id, Name);
cout<<articleArr[index].uId<<' '<<articleArr[index].uName<<endl;
}
我的代码问题是我无法创建一系列结构。编译器抛出了一个错误“ call to to to to artical :: article()”(文章* articlearr = new Artial [n];)行的错误。在我开始实施结构阵列的动态初始化之前,它效果很好。我必须使用char阵列,不允许使用字符串。
struct article {
int uId;
char uName[201];
article(int Id, char* name) { uId = Id;
for(int i=0;name[i]!='\0';i++)
{
uName[i]=name[i];
}
}
};
int main()
{
char Name[201];
int ID;
int N;
cin>>N;
article* articleArr = new article[N]; //error thrown on this line
/*Some code that creates ID and Name*/
articleArr[index] = article(Id, Name);
cout<<articleArr[index].uId<<' '<<articleArr[index].uName<<endl;
}
The problem I have with my code is that I can't dinamically create an array of structs. Compiler throws out an error "no matching function for call to 'article::article()" at the (article* articleArr = new article[N];) line. Before I started implementing dynamic initialization of array of structs it worked fine. I have to use char arrays, not allowed to use strings.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这条线
试图调用默认构造函数,但您没有一个。
您需要添加
C ++通常会自动为YO执行此操作,但是由于您给了构造函数C ++没有创建任何其他
btw-您应该真正使用
std :: vector
而不是'new''' 它更容易和更安全使用相同的使用是正确的。,对于
std :: String
而不是裸体char *
,This line
Is trying to invoke the default constructor but you do not have one.
You need to add
c++ would normally automatically do this for yo , but because you gave a constructor c++ did not create any others
BTW - you should really use
std::vector
rather that a 'new'ed array, its much easier and safer to usesame is true for
std::string
instead of nakedchar *
您已经声明了接受参数的构造函数。结果,该类将不会具有隐式生成的默认构造函数。由于您也没有定义构造函数,因此类也不是默认的构造。
该默认值构造了
n
类文章
的实例的数组。这是不正确的,因为该类不是默认的构造。潜在解决方案:
You have declared a constructor that accepts parameters. As a consequence, the class will not have an implicitly generated default constructor. Since you haven't defined a constructor either, the class is not default constructible.
This default constructs an array of
N
instances of the classarticle
. This is ill-formed because the class is not default constructible.Potential solutions: