使用 getters C++ 访问成员变量
Accessing member variables with getters C++
如果我的头文件中有这张私有场景图
std::map<std::string, Scene> scenes;
我的publicgetter也应该这样吗?
std::map<std::string, Scene>* getScenes() { return &scenes; }
我仍然在思考 C++ 中的指针,所以如果这看起来像一个愚蠢的问题,我深表歉意
除非您需要,return将指针指向未存储为指针的成员并不是一个好主意。传递指针可能会变得混乱,例如如果原始对象超出范围,您将得到一个悬空指针。通过 const 引用返回应该是您的第一个停靠港:
const std::map<std::string, Scene>& getScenes() const { return scenes; }
这将在保持 const 正确性的同时避免复制。这显然不是一种放之四海而皆准的方法,但如果您想要 getter 用于非原始类型,您通常会希望通过 const 引用 return。
考虑到您可以 return 通过引用,使用指针很少是个好主意。
std::map<std::string, Scene>& getScenes() { return scenes; }
但这也不是很好,并且违背了将成员变量设为私有的目的,return指向它的指针也是如此。
要访问成员变量以查看数据而不是更改它,这对具有私有成员变量的 getter 有一定的意义,您应该 return const 引用:
const std::map<std::string, Scene>& getScenes() const { return scenes; }
我只想补充一点,如果需要的话,一些人会捍卫 getters 和 setter are just clutter and you shoud just go ahead and make the member variable public。
其他人防守.
其他还在,that they sholud be used but only because they're the lesser o two evils.
如果我的头文件中有这张私有场景图
std::map<std::string, Scene> scenes;
我的publicgetter也应该这样吗?
std::map<std::string, Scene>* getScenes() { return &scenes; }
我仍然在思考 C++ 中的指针,所以如果这看起来像一个愚蠢的问题,我深表歉意
除非您需要,return将指针指向未存储为指针的成员并不是一个好主意。传递指针可能会变得混乱,例如如果原始对象超出范围,您将得到一个悬空指针。通过 const 引用返回应该是您的第一个停靠港:
const std::map<std::string, Scene>& getScenes() const { return scenes; }
这将在保持 const 正确性的同时避免复制。这显然不是一种放之四海而皆准的方法,但如果您想要 getter 用于非原始类型,您通常会希望通过 const 引用 return。
考虑到您可以 return 通过引用,使用指针很少是个好主意。
std::map<std::string, Scene>& getScenes() { return scenes; }
但这也不是很好,并且违背了将成员变量设为私有的目的,return指向它的指针也是如此。
要访问成员变量以查看数据而不是更改它,这对具有私有成员变量的 getter 有一定的意义,您应该 return const 引用:
const std::map<std::string, Scene>& getScenes() const { return scenes; }
我只想补充一点,如果需要的话,一些人会捍卫 getters 和 setter are just clutter and you shoud just go ahead and make the member variable public。
其他人防守
其他还在,that they sholud be used but only because they're the lesser o two evils.