【发布时间】:2017-04-01 14:16:17
【问题描述】:
我有一个带有引用的类,并且想要一个返回指针的 getter。
class X {
std::string& text;
public:
auto GetText() -> decltype(text) * { return &text); // doesn't work
X(std::string& text): text(text) {}
};
简单的方法是将指针传递给这个类。但是如果我传递一个引用,我可以得到一个带有 getter 的指针吗?
编辑:这是错误信息
error: cannot declare pointer to 'std::__cxx11::string& {aka class std::__cxx11::basic_string<char>&}'
auto GetText() -> decltype(text) * { return &text);
^
【问题讨论】:
-
“不起作用”不是一个有用的问题描述。你有编译错误吗?如果是这样,请将它们放在您的问题中。
-
为什么不直接做
std::string* GetText() { return &text; }?您的代码也有拼写错误(当然您的意思是}而不是)来关闭该功能)。 ` -
这一切似乎完全没有必要。
-
当您从字面上理解“始终自动”的闲置饮水机时会发生这种情况,并且完全没有任何反思地运行它。
-
strip the reference 可以,但为什么要这样做?正如 Kerrek 所说,这一切似乎完全没有必要。
标签: c++ class pointers reference getter