我正在写一个函数,我想返回"const std :: string&".我们来看看代码吧.
class A
{
public:
const std::string& GetString() const
{
if (list.empty())
{
return "Warning!"; // how to get around this line.
}
return list[0];
};
protected:
std::vector<std::string> list;
};
Run Code Online (Sandbox Code Playgroud)
以上代码就是一个例子.基本思想是编写一个返回const引用的函数,但也能够检查错误.
所以,如何绕过"返回"警告!";"?
谢谢,
if (list.empty()) {
static std::string w("Warning!");
return w;
}
Run Code Online (Sandbox Code Playgroud)
因为你要返回一个const引用,所以你总是返回对同一个对象的引用并不重要.