Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.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++ 如何为数组成员变量声明getter/setter_C++_Visual Studio_Compiler Errors - Fatal编程技术网

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

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

我想和学生们一起代表一门课程。学生们有他们的名字和姓氏,年龄。。。这些课程有一个名字和一个由3名学生组成的数组

我试图为数组定义getter和setter时出错

Error active E0415不存在从学生[3]转换为学生[3]的合适构造函数

Error active E0137表达式必须是可修改的左值

当然可以

#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();
};