【发布时间】: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