0

I am new to c++ and I have an error. When I created a new object the compiler giving to me " no suitable constructor exists to convert from const char[16] to stringex "and "no suitable constructor exists to convert from const char[14] to stringex "

#include <iostream>
    using namespace std;
    #include <stdlib.h>
    #include <string.h>
    class Stringex
    {
    private:
        enum{max=80};
        char str[max];
    public:
        Stringex() { strcpy(str, " "); }
        Stringex(char s[]) { strcpy(str, s); }
        void display()const
        {
            cout << str;
        }
        Stringex operator + (Stringex ss)const
        {
            Stringex temp;
            if (strlen(str) + strlen(ss.str) < max)
            {
                strcpy(temp.str, str);
                strcat(temp.str, ss.str);
            }
            else
            {
                cout << "\nString overflow!!!" << endl; exit(1);
            }
            return temp;
        }
    };
    int main()
    {
        Stringex s1 = "Merry Christmas!";
        Stringex s2 = "Happy new year!";
        Stringex s3;
        s1.display();
        s2.display();
        s3.display();
        s3 = s1 + s2;
        s3.display();
        return 0;
    }
Veysel Bozkurt
  • 53
  • 2
  • 11
  • 2
    `Stringex(const char s[]) { strcpy(str, s); }` should fix it. – πάντα ῥεῖ Sep 03 '20 at 13:45
  • 2
    I'm never convinced that rewriting the C++ standard library is a good beginner task. Obnoxiously, write `typedef std::string Stringex;` and program something more fun. You're already including the C++ standard library string header. – Bathsheba Sep 03 '20 at 13:50

1 Answers1

0

What is converted from string literals are const char*, so char[] (without const) cannot accept that.

You should add a constructor like

Stringex(const char* s) { strcpy(str, s); }

Avoiding buffer overrun by, for example, using strncpy() instead of strcpy() will improve your code more.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70