c++ - 如何修复“不存在从 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()
将更多地改进您的代码。
推荐阅读
- c++ - 禁止编译器警告
- javascript - 服务器运行时的Node.js javascript命令行?
- python - 如果数据类型是“时间戳”,我们可以过滤掉 z-score <-3 或 >3 的记录吗?
- node.js - 出现错误:表达式不可调用 Mongoose NextJS
- python - 如何将模糊匹配应用于数据框中的列
- javascript - 如何让这两个组件出现在同一行?(文本框标签和文本框)
- r - R:glm 中的起始值到底是什么以及如何指定?
- javascript - 在响应 onclick 中重定向到 index.html 文件
- typescript - TypeScript:如何使用变量推断类型在类之外定义另一个具有相同类型的变量
- c++ - 如何从 C++ 头文件中导出函数