我需要在c ++中为这些变量创建setter和getter的帮助。
char name[20];
double homeworkGrades[6];
double quizGrades[6];
double examGrades[4];
答案 0 :(得分:-1)
请求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,缓存等。