构造函数 (C++) 中的 char 指针参数存在问题

Problem with char pointer argument in a constructor (C++)

本文关键字:指针 参数 存在 问题 char 中的 C++ 构造函数      更新时间:2023-10-16

我不久前开始在一本书上学习C++,现在我被书中的部分代码困住了,这些代码不适用于我的API,即Visual Studio 2019。这本书是2000年的,所以这可能是问题的一部分,但如果是,你能告诉我如何修补它吗?

问题出在下面的代码中。本书的作者希望使用 char 数组作为构造函数的参数,并使用指针 (char* pName( 执行此操作。但是,Visual Studio强调了参数("0.丹尼男孩》(。我环顾四周寻找答案,但没有一个看起来像我的。如果有人能帮助我,将不胜感激!

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string.h>
using namespace std;
const int MAXNAMESIZE = 40;
class Student
{
public:
Student(char* pName)
{
strncpy_s(name, pName, MAXNAMESIZE);
name[MAXNAMESIZE - 1] = '';
semesterHours = 0;
gpa = 0;
}
//... autres membres publics...
protected:
char name[MAXNAMESIZE];
int semesterHours;
float gpa;
};
int main(int argcs, char* pArgs[])
{
Student s("0. DannyBoy");
Student* pS = new Student("E. Z. Rider");
system("pause");
return 0;
}

字符串文字属于const char []类型,衰减为const char *。您的构造函数应采用const char *

//      VVVVV
Student(const char* pName)
{
strncpy_s(name, pName, MAXNAMESIZE);
name[MAXNAMESIZE - 1] = '';
semesterHours = 0;
gpa = 0;
}

在这一行:

Student s("0. DannyBoy");

您正在将类型为char[12]的字符串文本传递给Student的构造函数。

但是,您需要使用char const *绑定到char数组,因此构造函数需要如下所示:

Student(char const * pName) {

在 C 中,历史上字符串文字具有非常量字符数组的类型。在 C++ 11 标准C++之前,编译器允许使用字符串文字作为具有非常量类型的参数的参数char *以实现向后兼容性。

但是,尽管在 C 字符串文字中具有非常量字符数组,但您不能更改它们。

在C++ 11 中,决定不允许将字符串文字与类型char *一起使用,因为C++它们具有常量字符数组的类型。

所以声明构造函数像

Student( const char *pName )

无论如何,它更好,因为此声明告诉类的读者,即使参数不是字符串文字,传递的字符串也不会在构造函数中更改。