C++使用和返回引用

Ony*_*gun 2 c++ string reference

看看以下功能:

std::string& foo (std::string& s)
{
  s.erase(0.s.find_first_not_of(" \f\t\v\r\n");
  return s;
}
Run Code Online (Sandbox Code Playgroud)

当一个字符串传入时,它会修改原始字符串吗?当您还要修改原始字符串时,为什么还要返回修改后的字符串?

试图更好地理解为什么某人可能以这种方式编码此功能?好吧有人这样做了所以我被问到为什么我只做以下事情:

std::string mystring = "    This is cool";
foo(mystring);
std::cout << mystring << std::endl;
Run Code Online (Sandbox Code Playgroud)

为什么我没有使用返回值?

R S*_*ahu 6

当一个字符串传入时,它会修改原始字符串吗?

那是正确的.

试图更好地理解为什么某人可能以这种方式编码此功能?

它允许链接函数调用.

在您的情况下,您可以使用:

std::cout << foo(mystring) << std::endl;
Run Code Online (Sandbox Code Playgroud)

链接函数调用的一个例子是如何operator<<使用std::cout.该operator<<函数返回一个参考ostream.因此,您可以使用:

std::cout << foo(mystring) << std::endl;
Run Code Online (Sandbox Code Playgroud)

否则,你将被迫使用:

std::cout << foo(mystring);
std::cout << std::endl;
Run Code Online (Sandbox Code Playgroud)

为什么我没有使用返回的值.

该语言不会强制您使用返回的值.但是,您可以使用它,如上所示.