Search code examples
c++wstring

How to change wstring value in struct?


I don't know how to change wstring value in struct . I don't know where is my error. do you help me ?

I can't understand why string value change success, wstring value change failed .

struct TestStruct{
  string falg1;
  wstring falg2;

  TestStruct setFlag1(string str ) {
    falg1 = str;
    return *this;
  }

  TestStruct setFlag2(wstring str ) {
    falg2 = str;
    return *this;
  }
};



int main(int argc,
         char ** argv) { 

      TestStruct testStruct;
      testStruct.setFlag1("string")
                .setFlag2(L"Wstring");
                
      wcout << "string length:" << testStruct.falg1.size() << endl;
      wcout << "Wstring content:" << '[' << testStruct.falg2 << ']' << endl;
      wcout << "Wstring length:" << '[' << testStruct.falg2.size() << ']' << endl;
}

The output content is :

string length:6
Wstring content:[]
Wstring length:[0]

Solution

  • I am not sure why are you trying to return a copy of your struct, the code looks really weird. I would use a method returning nothing and then setting the flags works as expected:

    #include <string>
    #include <iostream>
    
    struct TestStruct{
      std::string falg1;
      std::wstring falg2;
    
      void setFlag1(std::string str ) {
        falg1 = str;
      }
    
      void setFlag2(std::wstring str ) {
        falg2 = str;
      }
    };
    
    
    
    int main(int argc,
             char ** argv) { 
    
          TestStruct testStruct;
          testStruct.setFlag1("string");
          testStruct.setFlag2(L"Wstring");
                    
          std::wcout << "string length:" << testStruct.falg1.size() << std::endl;
          std::wcout << "Wstring content:" << '[' << testStruct.falg2 << ']' << std::endl;
          std::wcout << "Wstring length:" << '[' << testStruct.falg2.size() << ']' << std::endl;
    }
    

    Output:

    string length:6
    Wstring content:[Wstring]
    Wstring length:[7]
    

    As @Acanogua and @UnholySheep pointed out, it is also possible to return references and then chain the function calls as you tried in your example:

    struct TestStruct{
      std::string falg1;
      std::wstring falg2;
    
      TestStruct& setFlag1(std::string str ) {
        falg1 = str;
        return *this;
      }
    
      TestStruct& setFlag2(std::wstring str ) {
        falg2 = str;
        return *this;
      }
    };
    
    
    
    int main(int argc,
             char ** argv) { 
    
          TestStruct testStruct;
          testStruct.setFlag1("string").setFlag2(L"Wstring");
                    
          std::wcout << "string length:" << testStruct.falg1.size() << std::endl;
          std::wcout << "Wstring content:" << '[' << testStruct.falg2 << ']' << std::endl;
          std::wcout << "Wstring length:" << '[' << testStruct.falg2.size() << ']' << std::endl;
    }