我如何<vector>
用于需要通过构造函数赋值的对象数组?例如,具有名称、年龄的类将需要通过构造函数提供的信息进入数组Student(string n, int a ) { name = n , age = a }
。
所有数据将通过键盘给出..
这是一个能够使用向量获取和存储学生列表的姓名和年龄的程序示例代码。之后,它打印存储的信息。我使用 MSVC 作为编译器,所以如果你不在 Windows 上,你可以删除system("pause")
:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Student {
public:
Student(string n, int a) : name(n), age(a) {}
string GetName(void) { return name; }
int GetAge(void) { return age; }
private:
string name;
int age;
};
int main(void) {
vector<Student> students;
unsigned int n;
cout << "How many students are there?" << endl;
cin >> n;
for (unsigned int i = 0; i < n; ++i) {
string name;
int age;
cout << endl << "Please give me the information of the student " << i + 1 << endl;
cout << "What is the name of the student?" << endl;
cin >> name;
cout << "What is the age of the student?" << endl;
cin >> age;
students.push_back(Student(name, age));
}
cout << endl << "Printing information of the students" << endl << endl;
for (unsigned int i = 0; i < n; ++i) {
Student& student = students[i];
cout << "Student " << i + 1 << " is " << student.GetName() << " and is " << student.GetAge() << " years old." << endl;
}
system("pause");
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句