【问题标题】:How to find acess a class-method of objects stored in c++ vector?如何找到存储在 C++ 向量中的对象的类方法?
【发布时间】:2017-12-15 08:45:08
【问题描述】:

我是 C++ 菜鸟,如果这是一个简单的问题,请原谅我,从过去几天开始我一直在尝试解决这个问题。

存在一个名为 student 的类,它存储学生的姓名、年龄和分数。每个学生的个人资料(年龄、姓名和分数都存储在一个班级中)。一个班级中有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);
}

【问题讨论】:

  • 1) 您是否尝试过咨询您的C++ book? 2)您的具体问题是什么? SO 不是教程服务,目前,您的“问题”太宽泛了。
  • “我什至无法……” - 嗯,发生了什么事?它编译了吗?编译错误是什么?它崩溃了吗?显示了什么,您尝试过什么调试?还是输出不符合您的预期?
  • @Useless 它编译了所有的输入但没有给出任何输出
  • @AlgirdasPreidžius 我的问题是如何对存储在向量中的类的值使用类方法?

标签: c++ algorithm object stl


【解决方案1】:

vector &lt;student*&gt; library_stnd(n) 创建一个大小为n 的向量。然后在第一个 for 循环中 library_stnd.push_back(temp)temp 推到 library_stnd 的末尾并且不更改第一个 n 项。

问题是library_stnd 中的第一个n 项初始化为零[1],而在第二个for 循环中取消引用它是一种未定义的行为。[2]

我的建议是使用以下任一方法:

  1. vector &lt;student*&gt; library_stndlibrary_stnd.push_back(temp)
  2. vector &lt;student*&gt; library_stnd(n)library_stnd[i] = temp

另一个建议

  1. vector&lt;student&gt; 而不是 vector&lt;*student&gt;,然后是 for (auto&amp; ep: library_stnd)
  2. '\n' 而不是 endl [3]
  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"

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多