Jea*_*ffe 2 c++ syntax getter-setter
我有一个带有字符串属性的类,我的 getter 必须返回这些属性的 string& 值。
\n\n我设法做到这一点而没有出现错误的唯一方法是这样的:
\n\ninline string& Class::getStringAttribute() const{\n static string dup = stringAttribute;\n return dup;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n在 C++ 中编写返回私有字符串属性的字符串引用的 getter 的正确方法是什么?
\n\n这样做:
\n\ninline string& Class::getStringAttribute() const{\n return stringAttribute;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n给我这个错误:
\n\nerror: invalid initialization of reference of type \xe2\x80\x98std::string& {aka std::basic_string<char>&}\xe2\x80\x99 from expression of type \xe2\x80\x98const string {aka const std::basic_string<char>}\xe2\x80\x99\nRun Code Online (Sandbox Code Playgroud)\n
返回副本或 const 引用:
std::string get() const { return s_; }
const std::string& get() const { return s_; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3357 次 |
| 最近记录: |