【问题标题】:How can I fix " no suitable constructor exists to convert from const char"? [duplicate]如何修复“不存在从 const char 转换的合适构造函数”? [复制]
【发布时间】:2020-09-03 13:44:02
【问题描述】:

我是 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;
    }

【问题讨论】:

  • Stringex(const char s[]) { strcpy(str, s); } 应该修复它。
  • 我从不相信重写 C++ 标准库是一项很好的初学者任务。令人讨厌的是,写typedef std::string Stringex; 并编写更有趣的程序。您已经包含了 C++ 标准库字符串标头。

标签: c++ constructor operator-overloading strcpy string.h


【解决方案1】:

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

你应该添加一个构造函数

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

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

【讨论】:

  • 感谢您的反馈,感谢您,我解决了这个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-04
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多