为什么带有 const 关键字的构造函数可以工作,而没有它就不能工作?

Why does a constructor with a const keyword will work while it won't without it?

本文关键字:工作 就不能 const 关键字 为什么 构造函数      更新时间:2023-10-16

在这个例子中,来自Robert Lafore的C++书,作者没有使用const关键字,试图在Visual Studio 2017中执行相同的代码会给出下面列出的错误。我不确定作者在这里是否犯了错误。最终,添加一个 const 关键字为我解决了这种情况。

以下是错误,以防它们有所帮助:1- E0415 不存在合适的构造函数来从"const char [5]"转换为"字符串">

2-"初始化":无法从"常量字符[5]"转换为"字符串">

#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";
}
为什么

我必须使用常量,为什么作者省略了常量(这是故意的还是在他写这本书的时候没问题?

这是因为您传递给构造函数的"hey"是一个const char *,并且您不能将const值传递给声明为接受非const参数的函数。

当您使用以下行初始化字符串时,您实际上会为其提供const char *

String s1 = "hey";

但是,除非您有一个将const char *作为参数的构造函数,否则您基本上没有用于构建对象的构造函数。因为,const char *不能自动投射到char *。如果可以做到这一点,那么拥有一个const关键字就毫无意义了。

因此,如果您必须有一个将 char * 作为参数的 String 构造函数,那么您应该考虑将"hey"中的字符复制到 char 数组A,然后将A传递到构造函数中。

或者,只需保留const关键字。