【发布时间】:2021-03-13 16:10:30
【问题描述】:
我目前正在做一个项目,它是一个门票存储系统,将每个持票人存储为一个对象。
为了输入值,我使用了参数化构造函数。在主函数中,我为这些对象的数组声明了一个动态内存块。
我面临的主要问题是,在初始化每个对象的 for 循环中,循环只运行一次,然后终止。代码如下:
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
class node
{
string holder_name;
int age;
public:
node(string a, int b)
{
holder_name = a;
age = b;
}
void view()
{
cout << "Name: " << holder_name << endl;
cout << "Age: " << age << endl;
}
};
int main()
{
int count, i;
cout << "Enter no of nodes" << endl;
cin >> count;
node *arr = (node *)malloc(sizeof(node) * count);
for (i = 0; i < count; i++)
{
int b;
string str;
cout << "Enter name" << endl;
cin >> str;
cout << "Enter age" << endl;
cin >> b;
arr[i] = node(str, b);
arr[i].view();
}
return 0;
}
【问题讨论】:
-
不要在 C++ 中使用
malloc,而是使用std::vector。 -
for循环取决于用户输入。要获得更好的 minimal reproducible example,请删除该因素。 (如果我选择输入1,那么循环应该只运行一次。)而不是int count; cin >> count;硬编码一个值,如int count = 2;。您还可以从循环中删除用户输入,也许每个人的名字都是"Someone",他们的年龄是i。
标签: c++ oop data-structures memory-management malloc