Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 返回整个数组_C++_Class - Fatal编程技术网

C++ 返回整个数组

C++ 返回整个数组,c++,class,C++,Class,您可以使用数组元素的索引作为函数getcourt 比如说 How many courses are you currently taking? 2 What is your full name? Testing Name Type in 1 for Freshman, 2 for Sophomore, 3 for Junior or 4 for Senior. What year are you? 4 What is your current semester? Spring 2014 Plea

您可以使用数组元素的索引作为函数
getcourt

比如说

How many courses are you currently taking? 2
What is your full name? Testing Name
Type in 1 for Freshman, 2 for Sophomore, 3 for Junior or 4 for Senior.
What year are you? 4
What is your current semester? Spring 2014
Please enter the name of all your courses.
Course #1 : C++
Course #2 : Adv C++

Here is your information:
Name : Testing Name
Semester : Spring 2014
Year : Senior
Course #1 : C++
Course #2 : C++
string getCohort( int i ) const;
函数必须返回与给定索引对应的元素,如果索引无效,则返回空字符串

另一种方法是使用标准类
std::array
,并将其用作返回值。比如说

How many courses are you currently taking? 2
What is your full name? Testing Name
Type in 1 for Freshman, 2 for Sophomore, 3 for Junior or 4 for Senior.
What year are you? 4
What is your current semester? Spring 2014
Please enter the name of all your courses.
Course #1 : C++
Course #2 : Adv C++

Here is your information:
Name : Testing Name
Semester : Spring 2014
Year : Senior
Course #1 : C++
Course #2 : C++
string getCohort( int i ) const;
然后CName必须指向动态分配的数组,或者它应该是类型为
std::vector

比如说 std::向量CName; //

void setCourses(string courses[], int n);

#包括
//...
std::string*CName;
//...
void setCourses(const std::string courses[],int n)
{ 
CName=新标准::字符串[n];
std::副本(课程,课程+n,CName);
}

在最后一种情况下,不要忘记删除指针。

这是大量代码。你应该单独开发新函数,如果你准备了一个新函数,你的问题会得到更多的关注。正如你的另一个问题已经提到的:使用
std::vector
而不是普通数组和原始指针!不能返回数组,只能返回数组的指针,这本身就不安全,而且容易出错!另外,我没有得到你的
AmtClass
成员与你的关系,这背后的语义是什么??如果我应该使用向量,我会使用向量。AmtClass是收集有关我需要为数组创建空间的课程数量的信息strings@user3347541相信我,你应该为这个用例做好准备。其他任何东西都需要对代码进行更彻底的过度工作!在setcourse函数中,将数组更改为指针。@user3347541祝您好运。+1感谢您提到的
std::array
!恐怕,USER 334 741对使用标准C++的所有建议都是很有抵抗力的:虽然……我只是做我所要求的。“我不知道CNNE是什么意思。”不,等等,没关系,他只是用非常奇怪的方式使用数组。
void setCourses(string courses[], int n);
void setCourses( const std::string courses[], int n )
{ 
    CName.assign( courses, courses + n );
}
#include <algorithm>
//...

std::string *CName;
//...

void setCourses( const std::string courses[], int n )
{ 
    CName = new std::string[n];

    std::copy( courses, courses + n, CName );
}