gpt4 book ai didi

c++ - 这段代码是如何工作的?

转载 作者:太空狗 更新时间:2023-10-29 19:37:12 25 4
gpt4 key购买 nike

我在看 C++ for dummies 并找到这段代码

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

int nextStudentId = 1000; // first legal Student ID
class StudentId
{
public:
StudentId()
{
value = nextStudentId++;
cout << "Take next student id " << value << endl;
}

// int constructor allows user to assign id
StudentId(int id)
{
value = id;
cout << "Assign student id " << value << endl;
}
protected:
int value;
};

class Student
{
public:
Student(const char* pName)
{
cout << "constructing Student " << pName << endl;
name = pName;
semesterHours = 0;
gpa = 0.0;
}

protected:
string name;
int semesterHours;
float gpa;
StudentId id;
};

int main(int argcs, char* pArgs[])
{
// create a couple of students
Student s1("Chester");
Student s2("Trude");

// wait until user is ready before terminating program
// to allow the user to see the program results
system("PAUSE");
return 0;
}

这是输出

Take next student id 1000

constructing Student Chester

Take next student id 1001

constructing Student Trude

Press any key to continue . . .

我真的很难理解为什么第一个学生 id 是 1000,如果 value 加一个然后打印出来

这有意义吗

在 studentId 的构造函数中,两行代码将 nextStudentId 加一,然后打印出来

输出会不会是这样的:

Take next student id 1001

constructing Student Chester

Take next student id 1002

constructing Student Trude

Press any key to continue . . .

希望你明白我想说的

谢谢

卢克

最佳答案

++ 是自增运算符:它首先读取值(并将其分配给变量),然后 增加它。

将此与 pre 增量运算符进行对比:

value = ++nextStudentId;

这将具有您期望的行为。

查看此问题以获取更多信息:Incrementing in C++ - When to use x++ or ++x?

关于c++ - 这段代码是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4287612/

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