为什么带有 const 关键字的构造函数可以工作,而没有它就不能工作?
Why does a constructor with a const keyword will work while it won't without it?
在这个例子中,来自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
关键字。
相关文章:
- 为什么 HeapFree() 不能正常工作?
- std::unique_ptr 在 GCC 中工作,但不能在 Visual Studio 中编译
- 声明C++具有动态大小的数组类型在 Linux 中工作正常,但不能在 Windows 中工作
- 为什么"std::is_function_v"不能按预期工作?
- 为什么在C++中使用关系运算符创建的模板函数不能对字符串正常工作?
- std::remove() 按预期处理文字,但不能与取消引用的迭代器一起工作
- C++自定义删除运算符不能正常工作?
- 为什么使用 exec() 重新启动程序不能正常工作?
- C++:返回本地对象,但不能正常工作
- 有没有办法关闭文件? fclose 不能很好地工作
- 为什么我不能声明一个 constexpr 本地,而一个 const 一个工作?
- 为什么带有 const 关键字的构造函数可以工作,而没有它就不能工作?
- 实现快速排序,几乎可以工作但不能
- 为什么没有构造函数就不能创建对象?
- 为什么没有enable_if就不能编译
- Boost read_also()函数不能与Boost::array一起工作,不能使用std::array
- 如果一个引用一旦被初始化为一个对象,它就不能被改变,为什么这样做呢?
- 为什么当一个成员不能移动时,整个封闭类就不能移动
- 哪些c++操作符没有友元函数就不能重载
- 没有对象就不能调用成员函数