No suitable constructor exists to convert from const char to "custom string", though I have created one

1.3k Views Asked by At

I am doing a custom string class in C++. However, when I debugged my code, the system said that:

Error E0415:no suitable constructor exists to convert from "const char" to "string"

Here is my header file where my custom string class is defined:

#ifndef _STRING
#define _STRING
#include <iostream>

class string {
private:
    char* s = nullptr;
    unsigned int size = 0;

public:
    string();
    ~string() { delete s; };
    void operator=(const char*);
    friend std::ostream& operator<<(std::ostream&, string&);
};
#endif

string::string()
    : s{ nullptr }
{
    s = new char[1];
    s[0] = '\0';
}
void string::operator=(const char* source)
{
    if (source == nullptr) {
        s = new char[1];
        s[0] = '\0';
    }
    else {
        size = strlen(source) + 1;
        s = new char[size];
        for (int k = 1; k < (strlen(source) + 1); k++) {
            s[k] = source[k];
        }
    }
}
std::ostream& operator<<(std::ostream& output, string& result)
{
    output << result.s;
    return output;
}

And here is my main file which I tried to comply:

#include "custom_string.h"
int main()
{
    string a;
    a = "testfile";
    std::cout << a;
    system("pause");
    return 1;
}

As you can see, I have declared a constructor to convert const char to my custom string by overloading assignment operator. However, there should be something wrong in my code and I could not find out it. Please help me and thank you

1

There are 1 best solutions below

0
On

Thanks everyone, I have done to fix it. As it turned out, I have to declare one more constructor to covert between my custom string and const char. That is something like this:

string::string(const string& t){}

string& string::operator=(const char&source){}