使用函数更改 std::string 的内容

Sar*_*nyx 3 c++ string pointers

我觉得这个答案会快速而简单,但我现在似乎无法弄清楚。

 #include <string>
 #include <iostream>
 using namespace std;
 void change_thing (string x) {
      x="not thing";
 }
 int main() {
     string maybe_thing;
     maybe_thing="thing";
     change_thing(maybe_thing);
     cout << maybe_thing << endl;
     return 0;
 }
Run Code Online (Sandbox Code Playgroud)

当它打印出来时,我想 maybe_thing成为“不是东西”。我已经尝试了一堆不同的指针策略,但似乎没有任何效果(我很容易做错;无论如何,我对指针的了解是不完整的,因为我是 c++ 的新手)。

提前致谢!

McG*_*gle 5

您不需要指针,只需通过引用传递字符串即可:

void change_thing (string & x) {
    x="not thing";
}
Run Code Online (Sandbox Code Playgroud)