【问题标题】:How to declare getters/setters for an array member variable [duplicate]如何为数组成员变量声明 getter/setter [重复]
【发布时间】:2019-04-13 09:59:21
【问题描述】:

我正在尝试用学生代表一门课程。学生有关于他们的名字和姓氏、年龄的信息......课程有一个名字和一个由 3 个学生组成的数组。

我在尝试为数组定义 getter 和 setter 时遇到错误。

错误(活动)E0415 没有合适的构造函数来将“Student [3]”转换为“Student”

错误(活动)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;
}

我希望 get 的输出是学生数组。

【问题讨论】:

    标签: c++ visual-studio compiler-errors


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-26
      • 2011-06-22
      • 2017-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多