【问题标题】:Problem with char pointer argument in a constructor (C++)构造函数中的字符指针参数问题(C++)
【发布时间】:2020-10-07 11:59:03
【问题描述】:

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

问题出在以下代码中。本书的作者希望使用一个 char 数组作为构造函数的参数,并使用指针 (char* pName) 来实现。但是,Visual Studio 强调了参数(“0. DannyBoy”)。我环顾四周寻找答案,但没有一个看起来像我的。如果有人可以帮助我,将不胜感激!

#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] = '\0';
        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 Student(const char* pName) C++ 中的字符串文字具有常量字符数组的类型。
  • 你在用什么书?这在 2000 年也行不通。我可以推荐一个good C++ book吗?
  • 我开始在一本书上学习 C++ -- 不要从 20 多年前的书中学习。这本书是否还建议在不必要的时候使用new?喜欢这里:Student* pS = new Student("E. Z. Rider");?这应该是Student pS("E. Z. Rider");

标签: c++ pointers constants visual-studio-2019 string-literals


【解决方案1】:

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

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

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

所以像这样声明构造函数

Student( const char *pName )

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

【讨论】:

  • 感谢您的精彩解释!我添加了它,现在一切正常!
【解决方案2】:

在这一行:

Student s("0. DannyBoy");

您将一个字符串字面量(类型为char[12])传递给Student 的构造函数。

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

Student(char const * pName) {

【讨论】:

    【解决方案3】:

    字符串字面量的类型为const char [],它衰减为const char *。您的构造函数应该采用const char *:

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

    【讨论】:

      猜你喜欢
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多