c++ 没有匹配的构造函数?

标签 c++ string class constructor

我必须为大学项目创建一个自己的字符串类,到目前为止我的代码看起来像(我只显示相关部分):

class SuchString
{
    char* str;
    size_t siz;
public:
    SuchString(char* a);
    ~SuchString();
    SuchString(SuchString& a);
    SuchString operator+(const SuchString& a) const;
    ...
    ...
};

如您所见,我有一个char* 类型的构造函数,实现为:

SuchString::SuchString(char* a)
{
    siz = strlen(a);
    str = new char[siz];
    strcpy(str, a);
}

问题出在我的 operator+ 函数上:

SuchString SuchString::operator+(const SuchString &a) const
{
    return SuchString(strcat(str, a.str));
}

我收到以下错误消息:

No matching constructor for initialization of 'SuchString'

据我所知,strcat 函数应该返回一个 char*,我有一个该类型的构造函数。

我收到以下相同的错误消息:

SuchString SuchString::operator+(const SuchString &a) const
{
    char* lel = strcat(str, a.str);
    return SuchString(lel);
}

同样的事情又发生了。我预计代码 SuchString(lel) 会创建一个临时变量,因此函数可以随它一起返回,就像前面的示例一样。

感谢任何帮助。

ps:我知道创建这样的字符串类绝对是胡说八道,但这是大学的一些小项目。

最佳答案

SuchString(SuchString& a); 将非 const 引用作为参数,因此临时传递它是不可行的。你可能想要的是

SuchString(const SuchString& a);

因为当您按值返回时,会生成一个拷贝 - 即:

return SuchString(lel);

将创建一个临时的 SuchString,然后将其复制并返回。理论上,因为在实践中拷贝很可能被优化掉。

关于c++ 没有匹配的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29893211/

相关文章:

c++ - 如何保存 - 恢复所有 opengl 状态变量

c++ - 为什么指针用于 std::string.find?

r - R中plot函数如何查找regsubsets?

C++ : Allocation of an array attribute in a class

wordpress - 在 WordPress 中使用 acf 复选框将多个类分配给一个元素

c++ - Qt:c++ 信号到 qml 连接

c++ - C++ 中的递归 boolean 函数

C++ 如何遍历对象的 std::vector 并在控制台上显示内容

c++ - 如何忽略字符串中的重音以使其不改变其长度?

r - 将双字字符串中两个单词的第一个字母大写