首页 > 解决方案 > c++ 数组setter和getter

问题描述

我需要帮助在 c++ 中为这些变量制作 setter 和 getter。

char name[20];
    double homeworkGrades[6];
    double quizGrades[6];
    double examGrades[4];

标签: c++arrayssettergetter

解决方案


请求 setter 和 getter 意味着您有一个包含要封装的数据成员的类。这是一个例子:

class Student
{
public:
    explicit Student( std::string name )
        : _name{ std::move( name ) }
    {}

    std::string GetName() const { return _name; } // Getter only; set at construction time

    double GetHomework( int index ) const
    {
        return _homework.at( index ); // Throws if out of range
    }

    void SetHomework( int index, double grade )
    {
        _homework.at( index ) = grade;
    }

    // ...

private:
    const std::string     _name;
    std::array<double, 6> _homework;
    // ... etc.
};

Student 类的属性具有 getter 和 setter。优点是您可以进行错误检查(这里使用std::array::at()范围检查功能完成)、线程保护、文件/网络 I/O、缓存等。


推荐阅读