错误:找不到合适的构造函数,即使我已经做了一个,C ++ [英] error:no appropriate constructor found, even though i have made one,c++

查看:83
本文介绍了错误:找不到合适的构造函数,即使我已经做了一个,C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class String
{
    private:
        static const int SZ = 80;
        char str[SZ];
    public:
        String()
        {
            strcpy_s(str, " ");
        }
        String(char s[])
        {
            strcpy_s(str, s);
        }
}

这是我写的构造函数,请注意第二个

This is the constructor i have written, note the second one

在这里我正在使用它:

String s1 = "yes";
String s2 = "no";
String s3;

这是错误消息:

严重性代码描述项目文件行抑制状态错误(正在运行)E0415不存在从"const"转换的合适构造函数char [4]转换为" String"rishabh c ++项目F:\ rishabh c ++projects \ rishabh c ++ projects \ main.cpp 35

Severity Code Description Project File Line Suppression State Error (active) E0415 no suitable constructor exists to convert from "const char [4]" to "String" rishabh c++ projects F:\rishabh c++ projects\rishabh c++ projects\main.cpp 35

推荐答案

编译器告诉您,从字符串文字到任何可用的构造方法都没有隐式转换.其背后的原因是可以使用以下类型构造您的类 的类型:

The compiler is telling you there is no implicit cast from your string literal to any of the available constructors. The reason behind this is the types that your class can be constructed with:

String(char s[]);

请注意,根据C ++标准,字符串文字是常量.这将 not 隐式转换为构造函数所需的非常量类型.为此,需要 const_cast ,但请不要这样做!

Note that string literals are constant, as per the C++ standard. That will not be implicitly converted to the non-constant type that your constructor requires. To do that would require const_cast, but please don't do that!!!

如果您尝试显式构造,您还将得到一个错误(或至少一个警告):

You would also get an error (or at least a warning) if you attempted explicit construction:

String s1("yes");  // error

简单的解决方法是将参数更改为 const char [] (或者更常见的是 const char * ).

The simple fix is the change the parameter to const char[] (or indeed const char* is more commonly used).

String(const char *s)
{
    strcpy_s(str, s);
}

每当将指针或引用类型作为参数传递时,请始终问自己:我的函数是否需要修改参数的值?" -只要答案为否" 设为 const .

Whenever passing pointer or reference types as parameters, always ask yourself: "does my function need to modify the value of the parameter?" -- whenever the answer is "no" make it const.

这篇关于错误:找不到合适的构造函数,即使我已经做了一个,C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆