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;
}
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.