c++ - c++ 数组setter和getter
问题描述
我需要帮助在 c++ 中为这些变量制作 setter 和 getter。
char name[20];
double homeworkGrades[6];
double quizGrades[6];
double examGrades[4];
解决方案
请求 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、缓存等。
推荐阅读
- java - 使用复合自定义 _id 插入 Mongodb 时出现 MongoWriteException
- node.js - 安装“Yeogurt Generator”/NODE_ENV 错误
- javascript - (已解决)ReactJS。如何将数据从父组件隐式传输到子组件
- ruby - ruby selenium execute_script Net::ReadTimeout
- python - 如何显示熊猫数据框的子集?
- node.js - AWS ECS 更新服务擦除 mongo 容器
- c# - 如何在实时模式下单击鼠标更改文本框位置?
- pattern-matching - 如何使用 TUSTEP 查找行的最后一个字母
- python - 如何修复 TypeError:“NoneType”对象不支持项目分配
- sas - 仅基于变量值的空列 - SAS 数据集