有人可以解释C 操作员=此处的工作方式

Can someone explain how the c++ operator= here works?

本文关键字:工作 方式 操作员 解释      更新时间:2023-10-16

我有这个小的C 代码段,有人可以解释操作员如何在这里工作吗?

#include <iostream>
#include <string>
    using namespace std;
    static wstring & test() {
        static wstring test2;
        return test2;
   };

   int main()
   {
       test() = L"Then!";
       wcerr << test() << endl;
   }

函数test()正在将引用(不是副本(返回到静态变量test2。静态关键字使该函数test保持呼叫之间可变test2的值。因此,当您调用test()时,它会返回参考,允许您更改test()test2的值。这导致wcerr << test2 << endl;打印出"然后!"打印出来。

请注意,静态关键字的含义取决于上下文。使该函数静态使该函数仅可在文件中的其他函数中可见。如果将静态功能放在标题中,则该功能的每个#include都会减速。

您可能想说的是

#include <iostream>
#include <string>
using namespace std;
wstring & test() {
   static wstring test2;
   return test2;
}
int main()
{
   test() = L"Then!";
   wcerr << test() << endl;
}

函数 test()将a 参考返回到static变量test2。引用是指变量;您可以代替参考。

这等同于代码:

static wstring test2;
int main()
{
    test2 = L"Then!";
    wcerr << test2 << endl;
}

搜索您喜欢的C 引用"参考"。