Nir*_*lam 0 c++ structure class object
我有个问题。是否可以在运行时为类或结构创建多个对象?
#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;
}
Run Code Online (Sandbox Code Playgroud)
我尝试了上面的方法,但没有成功。任何帮助,将不胜感激
代替
for(i=0;i<4;i++)
{
struct node s[i];
}
Run Code Online (Sandbox Code Playgroud)
和
struct node s[4];
Run Code Online (Sandbox Code Playgroud)
你编写程序的方式将不起作用。您在块内定义了节点数组,因此它在该块之外不可见。
如果你想动态分配内存,你必须这样做:
struct node *s = new node[YourDesiredSize];
Run Code Online (Sandbox Code Playgroud)
或者如果你喜欢 c 风格(不推荐):
struct node *s;
s = (node*)malloc(YourDesiredSize * sizeof (node));
Run Code Online (Sandbox Code Playgroud)
并且不要忘记释放内存。
| 归档时间: |
|
| 查看次数: |
7849 次 |
| 最近记录: |