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

标签 c++ constructor constants

在此示例中,来自 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/

相关文章:

c++ - 如何在 C++/WinRT (`Promise.all` 等效项中等待多个可等待/IAsyncActions)?

c++ - 如何定义项目范围的常量或如何使我自己的类的成员函数在 C++ 中接受 const 对象

C++ 使用 Const int 定义数组

c++ - 将 zlib 与 mingw 一起使用

c++ - SDL2 无法正确绘制矩形

c++ - 到最近邻居的平均距离的近似值?

c# - 有没有办法用自己发起一个类?

c# - 继承一个没有任何构造函数的抽象类

java - 在类主体或构造函数中初始化类成员?

C++ 列表迭代器无法初始化