查看以下函数:
std::string& foo (std::string& s)
{
s.erase(0.s.find_first_not_of(" \f\t\v\r\n");
return s;
}
当传入一个字符串时,它确实会修改原始字符串,对吗?当您还修改原始字符串时,为什么要返回修改后的字符串?
试图更好地理解为什么有人可能以这种方式编写此函数的代码?好吧,有人这样做了,所以我被问到为什么我只做以下事情:
std::string mystring = " This is cool";
foo(mystring);
std::cout << mystring << std::endl;
为什么我不使用返回值?
最佳答案
When one passes in a string, it does modify the original string right?
没错。
Trying to better understand why someone might have coded this function this way?
它允许链接函数调用。
在您的情况下,您可以使用:
std::cout << foo(mystring) << std::endl;
函数调用链的一个例子是 operator<<
与 std::cout
一起使用. operator<<
函数返回对 ostream
的引用.因此,您可以使用:
std::cout << foo(mystring) << std::endl;
否则,您将被迫使用:
std::cout << foo(mystring);
std::cout << std::endl;
why I am not making use of the returned value.
该语言不会强制您使用返回值。但是,您可以使用它,如上所示。
关于C++ 使用和返回引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45924793/