C++ 如何为数组成员变量声明getter/setter
我想和学生们一起代表一门课程。学生们有他们的名字和姓氏,年龄。。。这些课程有一个名字和一个由3名学生组成的数组 我试图为数组定义getter和setter时出错 Error active E0415不存在从学生[3]转换为学生[3]的合适构造函数 Error active E0137表达式必须是可修改的左值 当然可以C++ 如何为数组成员变量声明getter/setter,c++,visual-studio,compiler-errors,C++,Visual Studio,Compiler Errors,我想和学生们一起代表一门课程。学生们有他们的名字和姓氏,年龄。。。这些课程有一个名字和一个由3名学生组成的数组 我试图为数组定义getter和setter时出错 Error active E0415不存在从学生[3]转换为学生[3]的合适构造函数 Error active E0137表达式必须是可修改的左值 当然可以 #pragma once #include "Student.h" #include "Teacher.h" class Course
#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();
};
Course.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;
}
我希望get的输出是学生数组。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();
};