gpt4 book ai didi

c++ - 为类/结构创建多个对象?

转载 作者:太空宇宙 更新时间:2023-11-04 15:51:24 24 4
gpt4 key购买 nike

我有一个问题。是否可以在运行时为类或结构创建多个对象?

#include<iostream>
#include<conio.h>
using namespace std;
struct node
{
int no;
};

int main()
{
int i;
for(i=0;i<4;i++)
{
struct node s[i];
}
cout<<"Enter the values";
for(i=0;i<4;i++)
{
cin>>s[i].no;
}
cout<<"The values are:";
for(i=0;i<4;i++)
{
cout<<s[i].no<<endl;
}
getch();
return 0;
}

我试过上面的方法,但是没有成功。任何帮助将不胜感激

最佳答案

替换

for(i=0;i<4;i++)
{
struct node s[i];
}

 struct node s[4];

您编写程序的方式将行不通。您在 block 内定义了节点数组 s,因此它在该 block 外不可见。

如果你想动态分配内存,你必须这样做:

 struct node *s = new node[YourDesiredSize];

或者如果你喜欢 c 风格(不推荐):

 struct node *s;
s = (node*)malloc(YourDesiredSize * sizeof (node));

不要忘记释放内存。

关于c++ - 为类/结构创建多个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7671719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com