我是 C++ 菜鸟,如果这是一个简单的问题,请原谅我,过去几天我一直在努力解决这个问题。
存在一个名为student 的类,它存储学生的姓名、年龄和分数。每个学生的个人资料(年龄、姓名和分数存储在一个类(class)中)。有n
一个类(class)的学生因此,一个vector<student*>
已创建,它存储指向类(class)中所有学生个人资料的指针。
我想打印存储在 `vector 中的值 我真的很感激任何提示!
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
using namespace std;
class student{
private:
string name;
float marks;
int age;
public:
student(): name("Null"), marks(0),age(0){}
student(string n, float m,int a): name(n), marks(m),age(a){}
void set_name();
void set_marks();
void set_age();
void get_name();
void get_marks();
void get_age();
};
void student::set_name(){
cout<<"Enter the name: ";
cin >> name;
}
void student::set_age(){
cout << "Enter the age: ";
cin >> age;
}
void student::set_marks(){
cout<<"Enter the marks ";
cin>> marks;
}
void student::get_name(){
cout<<"Name: "<< name<<endl;
}
void student::get_age(){
cout<<"Age: "<< age<<endl;
}
void student::get_marks(){
cout<<"Marks: "<< marks<<endl;
}
int main() {
int n;
cout<<"Enter the number of students: ";
cin >> n;
vector <student*> library_stnd(n);
for(int i=0;i<n;i++){
student* temp = new student;
temp->set_name();
temp->set_age();
temp->set_marks();
library_stnd.push_back(temp);
}
for (auto ep: library_stnd){
ep->get_age();
}
return(0);
}
最佳答案
vector <student*> library_stnd(n)
创建一个大小为 n
的 vector .然后在第一个for循环中library_stnd.push_back(temp)
推 temp
到 library_stnd 的末尾并且不首先更改 n
项目。
问题是第一个n
library_stnd
中的项目零初始化[1] 并且在第二个 for 循环中取消引用它是未定义的行为。[2]
我的建议是使用以下任一方法:
-
vector <student*> library_stnd
和library_stnd.push_back(temp)
-
vector <student*> library_stnd(n)
和library_stnd[i] = temp
另一个建议
-
vector<student>
而不是vector<*student>
, 然后for (auto& ep: library_stnd)
-
'\n'
而不是endl
[3] -
double
而不是float
[4]
[1] - What is the default constructor for C++ pointer?
[2] - C++ standard: dereferencing NULL pointer to get a reference?
[3] - C++: "std::endl" vs "\n"
关于c++ - 如何找到存储在 C++ vector 中的对象的类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47828667/