C++ 使用和返回引用

标签 c++ string reference

查看以下函数:

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/

相关文章:

c++ - 如何管理多个字符数组变量?

c++ - 需要帮助追踪 MacOS 上函数入口的 EXC_BAD_ACCESS

string - 将算法的大 O 表示法从 O(n^2) 改进为更好的东西

python - 从 for 循环中更新外部范围变量值的最佳方法?

c++ - 在 C++ 中返回 vector 标准

php - 注意:数组到字符串的转换 - 为什么?

c++ - 在 C++ 中将大于 5 位的数字除以 2 时会失去精度

c++ - Call Base 默认构造函数模板类

java - 字符串修剪出来的长度不正确

php - 是否允许在文档中设置return to json?