Search code examples
c++operator-overloadingassignment-operatorwchar-t

overloading operator for string in c++


I have a class named Fstring, it has a wchar_t* in it.

I wrote the following to copy the string literal into Fstring:

#include <iostream>
using namespace std;
class Fstring{
    wchar_t *arr;
public:

    Fstring& operator = (const wchar_t temp[])
    {
        delete [] arr;
        arr=new wchar_t[wcslen(temp)];
        for(int i=0;i<=wcslen(temp);i++)
            arr[i]=temp[i];
        return *this;
    }
};

int main()
{
    Fstring test=L"Hello World";

    return 0;
}

But it did not work. The compiler gave me the following error:

error C2440: 'initializing' : cannot convert from 'const wchar_t [12]' to 'Fstring'

I'm really confused, I googled "Overloading operators" but all of results have the same way I used to overload the operator. So why does this not work?


Solution

  • When you see Type name = initializer it does not use the assignment operator. It is declaring a variable and is therefore initialization(technically copy-initialization or copy-list-initialization). That means it calls a constructor. Since you do not have a constructor that takes a const wchar_t* you will get an error.

    What you need is to implement a constructor that takes a const wchar_t* and initialize arr with that. That would look like

    Fstring(const wchar_t temp*) : arr(new wchar_t[wcslen(temp) + 1])
    {
        size_t size = wcslen(temp);
        for(int i = 0; i < size; i++)
            arr[i] = temp[i];
        arr[size] = L'\0'
    }
    

    You are also going to have to implement a copy constructor. For more on why see What is The Rule of Three?


    Do note that you are reinventing the wheel. If you want a wide character string you can use std::wstring which has all this done for you.