c++ - 如何在函数中更新 C++ 字符串?

标签 c++ string arduino arduino-uno

<分区>

假设我想编写一个 C++ 函数 foo() 来更新输入字符串的值。我该怎么做?代码可能看起来像我下面的代码,但我不知道如何正确传递字符串,以便它由函数更新。

void foo(String x) // Not sure if I should put an & or * before x
{
    x += " Goodbye";
}

void main()
{
    String x = "Hello World";
    cout << "x = " << x << endl;
    foo(x);  // Not sure if I should pass a pointer to x,
             // a reference to x or what?

    cout << "After foo (), x = " << x << endl;
}

(仅供引用,我正在为 Arduino 处理器编写此代码)

最佳答案

通过引用传递:

void foo(String& x)
{
    x += " Goodbye";
}

& 表示参数是函数外部对 String 的引用,而不是拷贝。

关于c++ - 如何在函数中更新 C++ 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29958097/

相关文章:

c++ - 使用 cin.eof()

c++ - 使用 HDF5 保存要在 C++ 中读取的 MATLAB 结构

c++ - 如何在 C++ 字符串中搜索非 ASCII 字符?

c++ - 没有调用未解析的重载函数类型的匹配函数

c++ - 为什么找不到一个Visual Studio#包含两个文件?

c++ - 提升asio服务器以了解客户端何时关闭套接字

c - 如何在我的 C 字符串前面插入单个字符?

python - 使用Python在字符串中查找unicode字符

c++ - 将空终止的 const char* 字符串数组转换为 std::vector< std::string >

python - 使用GPRS扩展板和AT命令将arduino传感器数据发送到服务器