简体   繁体   中英

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

I have this small c++ code snippet, may someone explain how the operator= works here ?

#include <iostream>
#include <string>

    using namespace std;

    static wstring & test() {
        static wstring test2;
        return test2;
   };


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

The function test() is returning a reference (not a copy) to the static variable test2 . The static keyword makes the function test maintain the value of variable test2 between calls. Hence when you call test() it returns the reference allowing you to change the value of test2 inside the test() . This results in wcerr << test2 << endl; printing out "Then!"

Note the static keyword has different meaning depending on the context. Making the function static makes the the function only visible to other functions in the file. If you put a static function in a header you will have deceleration for that function for each #include of that header.

What you probably wanted to say is

#include <iostream>
#include <string>

using namespace std;

wstring & test() {
   static wstring test2;
   return test2;
}

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

The function test() returns a reference to the static variable test2 . A reference refers to a variable; you could substitute the variable in place of the reference.

This is equivalent to the code:

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

Search your favorite C++ reference for "references".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM