如何为数组成员变量声明 getter/setter
How to declare getters/setters for an array member variable
我正在尝试与学生一起表示课程。学生有关于他们的名字和姓氏,年龄的信息...课程有一个名称和 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();
};
相关文章:
- .cpp和.h文件中的模板专用化声明
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- #ifdef和未声明的标识符
- 没有显式声明的int[]中的foreach
- 在基于范围的for循环中使用结构化绑定声明
- 在将变量声明为引用时,堆在释放后使用
- C++:无法访问声明的受保护成员
- 如何通过 getter 函数删除矢量的元素?
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 在函数内部的声明中初始化数组,并在外部使用它
- Visual Studio中的函数声明和函数定义问题
- 如何为数组成员变量声明 getter/setter