【发布时间】:2016-04-15 23:25:20
【问题描述】:
我正在尝试创建一个学生结构,然后在该结构内有一个基于用户输入的分数(或分数)数组。
然后,我尝试创建 Student 结构的动态数组。
我想与这些指针交互,即输入学生信息和成绩,然后计算它们,但我认为我没有正确执行此操作。这是我的代码开头的一段。我的主要问题是创建一系列标记,我在教科书中找不到如何声明它。
#include <string.h>
#include <iostream>
#include <sstream>
using namespace std;
struct Student
{
string name;
int id;
int* mark;
~Student()
{
delete [] mark;
mark = NULL;
};
};
void initStudent(Student* ptr, int markNum, int studentNum ); // function prototype for initialization
void sayStudent(Student* ptr, int markNum, int studentNum); // function prototype for printing
//*********************** Main Function ************************//
int main ()
{
int marks, studentNum;
Student stu; // instantiating an STUDENT object
Student* stuPtr = &stu; // defining a pointer for the object
cout << "How many marks are there? ";
cin >> marks;
cout << "How many students are there?";
cin >> studentNum;
Student* mark = new int[marks];
Student* students = new Student[studentNum];
initStudent(students,marks,studentNum); // initializing the object
sayStudent(students,marks,studentNum); // printing the object
delete [] students;
return 0;
} // end main
//-----------------Start of functions----------------------------//
void initStudent(Student* ptr, int markNum, int studentNum)
{
for (int i = 0; i < studentNum; i++)
{
cout << "Enter Student " << i+1 << " Name :";
cin >> ptr[i].name;
cout << "Enter Student ID Number :";
cin >> ptr[i].id;
for (int j = 0; j < markNum; j++)
{
cout << "Please enter a mark :";
cin >> ptr[i].mark[j];
}
}
}
【问题讨论】:
-
我在教科书中找不到如何声明它。 --
std::vector<int>std::vector<Student>-- 再找一本教科书。 -
@PaulMcKenzie 我需要动态分配内存。不只是创建一个向量。
-
@RoyGunderson “我需要动态分配内存。”你认为
std::vector实际上做了什么? -
我可以建议
Student中的构造函数而不是initStudent吗? -
@RoyGunderson 然后我尝试创建一个 Student 结构的动态数组 -- C++ 中的动态数组是
std::vector。