如何为数组成员变量声明 getter/setter



我正在尝试与学生一起表示课程。学生有关于他们的名字和姓氏,年龄的信息...课程有一个名称和 3 名学生的数组。

当我尝试为数组定义 getter 和 setter 时,我收到错误。

错误(活动)E0415 不存在合适的构造函数来从"学生 [3]"转换为"学生">

错误(活动)E0137 表达式必须是可修改的左值

课程.h

#pragma once
#include "Student.h"
#include "Teacher.h"

class Course
{
private:
string name;
Student students[3];
Teacher teacher;
public:
Course();
~Course();
void setName(string name);
string getName();
void setStudents(Student students[3]);
[3] Student getStudents();
};

当然.cpp

#include <iostream>
#include "Course.h"
#include "Student.h"
#include "Teacher.h"
using namespace std;
Course::Course() {}
Course::~Course()
{
}
void Course::setName(string name)
{
this->name = name;
}
string Course::getName()
{
return this->name;
}
void Course::setStudents(Student students[3])
{
/*for (int i = 0; i < 3; i++) {
this->students[i] = students[i];
}*/ 
//This way the set works
this->students = students;
}
[3]Student Course::getStudents()
{
return this->students;
}

我希望得到的输出是学生的阵列。

C 样式数组无法复制,无法自动分配,也无法从函数返回。

值得庆幸的是,C++标准库在实现所有这些操作的 C 样式数组上提供了一个精简包装类。它被称为std::array,它可以像您尝试使用 C 样式数组一样使用。

#pragma once
#include "Student.h"
#include "Teacher.h"
#include <array>
class Course
{
private:
string name;
std::array<Student, 3> students;
Teacher teacher;
public:
Course();
~Course();
void setName(string name);
string getName();
void setStudents(std::array<Student, 3> students);
std::array<Student, 3> getStudents();
};

最新更新