c++ - C ++如何从函数返回对象数组
问题描述
最近我开始学习 c++,所以我正在尝试使用我的基础知识制作一个简单的成绩计算器(我已经精通 Javascript,所以我知道编程的基础知识)。
所以在这种情况下,我必须从函数调用中返回一个对象数组,以便稍后在程序中使用它,但我找不到正确的方法。
所以基本上我想subArr
从getInput
函数中返回,但由于我的语言基础知识,我无法做到这一点。我尝试使用谷歌搜索,但没有找到任何简单的解决方案。
这是代码,希望它很简单:
//the Subject class:
class Subject {
public:
string name;
float grade;
int factor;
Subject(){};
Subject(string x, float y, int z){
name = x;
grade = y;
factor = z;
}
};
//get Input function declaration
Subject getInput(int num){
//array of objects of type "Subject"
Subject subArr[num];
//a for loop to assign the array's elements
for(int i = 0; i < num; i++){
string name;
float grade;
int factor;
cout << "what is the name of subject " << i+1 <<"? "<<endl;
cin >> name;
cout << "what is the grade of subject " << i+1 << "? "<<endl;
cin >> grade;
cout << "what is the factor of subject " << i+1 << "? "<<endl;
cin >> factor;
subArr[i]=Subject(name, grade, factor);
};
//trying to return the subArr at last
return subArr;
};
//main function
int main(){
//get the number of subjects
int numOfSubjects;
cout << "how many subjects are there? ";
cin >> numOfSubjects;
//trying to receive the subArr from getInput call
Subject subArr = getInput(numOfSubjects);
};
解决方案
使用std::vector
:
#include <iostream>
#include <vector>
using namespace std;
// the Subject class
class Subject {
public:
string name;
float grade;
int factor;
Subject(){};
Subject(string x, float y, int z){
name = x;
grade = y;
factor = z;
}
};
// get Input function declaration
vector<Subject> getInput(int num){
// array of objects of type "Subject"
vector<Subject> subArr;
// a for loop to assign the array's elements
for(int i = 0; i < num; i++){
string name;
float grade;
int factor;
cout << "what is the name of subject " << i+1 <<"? "<<endl;
cin >> name;
cout << "what is the grade of subject " << i+1 << "? "<<endl;
cin >> grade;
cout << "what is the factor of subject " << i+1 << "? "<<endl;
cin >> factor;
subArr.push_back(Subject(name, grade, factor));
};
// trying to return the subArr at last
return subArr;
};
// main function
int main(){
// get the number of subjects
int numOfSubjects;
cout << "how many subjects are there? ";
cin >> numOfSubjects;
// trying to receive the subArr from getInput call
vector<Subject> subArr = getInput(numOfSubjects);
};
推荐阅读
- html - 如何创建描述列表?
- c# - Microsoft 的 WebView 组件不显示本地页面
- serverless - 由于状态机定义错误,无服务器部署失败
- bash - 在 BASH 中将字符串字符转换为整数
- python-3.x - 发生异常:ImportError Python
- r - 跨列表中的多个数据框更改单个列
- angular - 使用 Angular 在 DevExtreme 中自定义动态字段
- c# - 如何在 Visual Studio for c# 中更改启动代码?
- javascript - 如何触发 AsyncSelect 以重新加载 ReactJS 中的选项
- ionic-framework - 如何在 ionic v4 中禁用启动画面微调器?