【发布时间】: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