首页 > 解决方案 > 如何修复“不存在从 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;
    }

标签: c++constructoroperator-overloadingstrcpystring.h

解决方案


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

您应该添加一个构造函数,例如

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

避免缓冲区溢出,例如,使用strncpy()而不是strcpy()将更多地改进您的代码。


推荐阅读