在此示例中,来自 Robert Lafore 的 C++ 书籍,作者没有使用 const 关键字,但是,尝试在 Visual Studio 2017 中执行相同的代码会出现下面列出的错误。我不确定作者在这里是否犯了错误。最终,添加一个 const 关键字为我解决了这个问题。
如果有帮助,以下是错误: 1- E0415 不存在合适的构造函数来将“const char [5]”转换为“String”
2- 'initializing': 无法从 'const char [5]' 转换为 'String'
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
class String {
/*
.
.
.
*/
String(const char s[]) { //Please note that actually there is no const keyword in the book. I've just put it in there.
strcpy_s(str, s);
}
/*
.
.
.
*/
};
int main() {
String s1 = "hey";
}
为什么我必须使用 const,为什么作者省略了那个 const(这是故意的还是在他写这本书的时候已经可以了?)?
最佳答案
那是因为你传递给构造函数的 "hey"
是一个 const char *
而你不能传递一个 const
声明为采用非 const
参数的函数的值。
关于c++ - 为什么带有 const 关键字的构造函数可以工作,而没有它就不行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49762900/