gpt4 book ai didi

c++ - 为什么新的 Visual Studio 将字符串文字作为指向常量的指针?

转载 作者:行者123 更新时间:2023-12-03 07:07:00 24 4
gpt4 key购买 nike

我为我的类(class)学生准备了这个构造函数。

student::student( char* rollno ,   char* name , date dob) :
rollno(rollno), name(name),dob(dob)
{
}
当我写 student s1( "l1f18bscs0322" , "usama" , { 13,7,1998 });总的来说,我认为它在我的大学接受它是因为它使用 Visual Studio 2013,但它给出了错误
在家里,因为我正在使用 Visual Studio 2019。它说没有构造函数的实例与参数列表匹配,它将双引号中的值作为指向常量的指针。将值传递给此构造函数的替代方法是什么?因为即使我将构造函数原型(prototype)更改为指向指针的常量,也会给出新的错误,即我无法用常量初始化非常量成员。

最佳答案

因为它是!
在 C++ 中,字符串文字的类型是 const char[N] (其中 N 是字符串的长度,包括其空终止符)。衰减到 const char* ,而不是 char* .
在 C++ 的早期版本(2011 年之前)中,您可以“忘记”const为了与 C 兼容,尽管这样做已被弃用(并试图“修改”文字具有未定义的行为)。从那时起,您必须编写它。
您已升级到 a version of Visual Studio that enforces this rule ,可能只是因为它的默认 C++ 标准是 C++11 或更高版本。
那是一件好事;添加 const .
如果您的类(class) Material 使用 char*在这里,它已经过时了,并且在某种意义上总是“错误的”。

even If I change my constructor protype to constant to pointer so it will give new error that I cannot initialize my non constant members with constant


你需要对你的成员变量做同样的事情。

关于c++ - 为什么新的 Visual Studio 将字符串文字作为指向常量的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65076611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com