如何解决“不存在从const char转换的合适构造函数”?

问题描述

我是C ++的新手,但出现错误。当我创建一个新对象时,编译器会告诉我“不存在从const char [16]转换为stringex的合适的构造函数”和“不存在从const char [14]转换为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;
    }

解决方法

从字符串文字转换的是const char*,因此char[](没有const)不能接受。

您应该添加类似的构造函数

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

例如,通过使用strncpy()而不是strcpy()来避免缓冲区溢出,将会大大改善代码。