小编Jea*_*ffe的帖子

getter 中返回字符串引用的正确方法

我有一个带有字符串属性的类,我的 getter 必须返回这些属性的 string& 值。

\n\n

我设法做到这一点而没有出现错误的唯一方法是这样的:

\n\n
inline string& Class::getStringAttribute() const{\n    static string dup = stringAttribute;\n    return dup;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

在 C++ 中编写返回私有字符串属性的字符串引用的 getter 的正确方法是什么?

\n\n

这样做:

\n\n
inline string& Class::getStringAttribute() const{\n    return stringAttribute;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

给我这个错误:

\n\n
error: 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\n
Run Code Online (Sandbox Code Playgroud)\n

c++ syntax getter-setter

2
推荐指数
1
解决办法
3357
查看次数

标签 统计

c++ ×1

getter-setter ×1

syntax ×1