如何找到C 向量中存储的对象的类方法

How to find acess a class-method of objects stored in c++ vector?

本文关键字:存储 对象 类方法 向量 何找      更新时间:2023-10-16

我是c 菜鸟,如果这个简单的问题,我一直在尝试解决这个问题。

存在一个名为"学生"的课程,该课程存储了学生的名字,年龄和标记。每个学生的个人资料(年龄,名称和标记都存储在班级中)。在课堂上有n学生,因此创建了vector<student*>,它将指针存储在课堂上的所有学生中。

我想打印存储在`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的向量。然后,在第一个循环中,library_stnd.push_back(temp)temp推到Library_stnd的末尾,并且不更改第一个n项目。

问题是library_stnd中的第一个n项目是零初始化[1],并且在第二个循环中将其删除是一种不确定的行为。[2]

我的建议是使用以下任何一个:

  1. vector <student*> library_stndlibrary_stnd.push_back(temp)
  2. vector <student*> library_stnd(n)library_stnd[i] = temp

另一个建议

  1. vector<student>代替vector<*student>,然后for (auto& ep: library_stnd)
  2. 'n'代替endl [3]
  3. double而不是float [4]

[1] - C 指针的默认构造函数是什么?

[2] - C 标准:取消定义null指针以获取参考?

[3] - C :std :: endl&quot;VS" n&quot"

[4] - https://softwareengineering.stackexchange.com/questions/188721/when-do-you-use-float-and-when-do-you-use-use-use-use-use-double