kmi*_*las 3 c++ oop getter encapsulation const
当我在学校时,教授们把它敲进了我的脑海,同事们在代码审查中跳了起来,而且几乎所有的C++教科书都在那里:"访问者"(又名"选择器"或"getter")方法必须被标记const.如果它没有改变或改变数据,则标记它const.
为什么?如何调用访问者来修改私有数据?
在下面的示例中,我设置了一个简单的类和一个访问器.如何getBrand()用于修改私有数据?在我眼里,它不能; 那么我们为什么需要标记呢const?
换句话说,我是否正确地说getBrand()在实践中不可能改变私有财产?
例:
#include <iostream>
#include <string>
class Cheese {
public:
Cheese(std::string brand):brand_(brand) {}
std::string getBrand() { return brand_; } // Intentionally not marked const
private:
std::string brand_;
};
int main() {
Cheese cheddar("Cabot clothbound");
std::cout << "Brand: " << cheddar.getBrand() << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
ein*_*ica 10
它实际上非常简单:如果方法不是const,你将无法在const对象上使用它- 但你确实希望能够使用它.在你的课上,你无法实现
void print_brand(const Cheese& cheese);
Run Code Online (Sandbox Code Playgroud)
(除非你是const-cast,你不应该这样做).
此外,如果你确实使它成为const,而不是返回你的字符串的副本 - 可能会或可能不会被优化,你可以实现:
const std::string& getBrand() const { return brand_; }
Run Code Online (Sandbox Code Playgroud)
它返回一个引用,或者也许
std::string_view getBrand() const { return brand_; }
Run Code Online (Sandbox Code Playgroud)
不会将你的API"提交"到字符串类(在string_view 这里阅读;它只是在C++ 17中正式添加到语言中,但是std::experimental::string_view与最近的编译器一样可用).