如何找到C 向量中存储的对象的类方法
How to find acess a class-method of objects stored in c++ vector?
我是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]
我的建议是使用以下任何一个:
-
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] - 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
相关文章:
- 如何使用 stl 容器有效地存储对象?(即根据其字段的值进行搜索)
- 线程上下文上的静态存储对象优化
- OOP - 存储对象和服务接口
- 为什么存储对象地址在缓冲区中会导致内存泄漏并删除它们
- 是否保证在销毁所有线程本地存储对象后销毁全局对象
- 使用列表存储对象
- 在c++中存储一个对象或不存储对象的首选方式是什么
- 更好的是:存储对象与存储指针
- 应用程序使用QMAP存储对象时停止响应
- 使用堆栈存储对象
- 如何在 std::map 中存储"对象类型"?
- 我应该如何存储对象
- 在 c++ 中存储对象的最佳策略是什么,确保名称唯一并能够在以后有效地检索它们
- 用于存储对象列表的最佳标准类
- 在C++中存储对象地址的数据结构
- 函子如何维护/存储对象的状态
- 我如何定义一个向量,并用C++在其中存储对象
- 存储对象以备将来使用(在重新启动程序时)
- C++/JNI-存储对象(jobject)在向量和数组中发生意外更改,C++或JNI问题
- 在多个容器中存储对象的最佳实践