C++中vector的使用,求解答!
student_student;vector<student>vstudent(N);for(inti=0;i<n;i++){cout<<"Pleaseenterage:...
student _student;
vector<student>vstudent(N);
for(int i=0;i<n;i++)
{
cout<< "Please enter age:";
cin >> _student.age;
cout<< "Please enter ID:";
cin >> _student.ID;
cout<< "Please enter name:";
cin >> _student.name;
vstudent.push_back(_student);
}
for (int i=0; i<n; i++)
cout << vstudent[i].age<<endl;
分别输入age ID name 之后,最后一句cout << vstudent[i].age<<endl;为什么输出的两个值都为零?
push_back不是一次存入的吗? 展开
vector<student>vstudent(N);
for(int i=0;i<n;i++)
{
cout<< "Please enter age:";
cin >> _student.age;
cout<< "Please enter ID:";
cin >> _student.ID;
cout<< "Please enter name:";
cin >> _student.name;
vstudent.push_back(_student);
}
for (int i=0; i<n; i++)
cout << vstudent[i].age<<endl;
分别输入age ID name 之后,最后一句cout << vstudent[i].age<<endl;为什么输出的两个值都为零?
push_back不是一次存入的吗? 展开
1个回答
展开全部
vector<student>vstudent(N);这条语句,默认使用student的默认构造器进行了初始化,也就是说你的学生类默认构造器中将age置为0了!
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class student{
public:
int age;
string ID;
string name;
student(){
age = 0;
ID = "";
name ="";
}
};
const int N = 2;
int main(){
vector<student> vstudent;
for(int i=0; i < N; i++){
student _student;
cout<< "Please enter age:";
cin >> _student.age;
cout<<_student.age;
cout<< "Please enter ID:";
cin >> _student.ID;
cout<< "Please enter name:";
cin >> _student.name;
vstudent.push_back(_student);
}
for (int i=0; i < N; i++)
cout << vstudent[i].age<<endl;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询