加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 此代码如何工作?

发布时间:2020-12-16 10:45:37 所属栏目:百科 来源:网络整理
导读:我正在寻找傻瓜的c并找到了这段代码 #include cstdio#include cstdlib#include iostreamusing namespace std;int nextStudentId = 1000; // first legal Student IDclass StudentId{public:StudentId(){ value = nextStudentId++; cout "Take next student i
我正在寻找傻瓜的c并找到了这段代码

#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,如果值加一个然后将其打印出来

这有道理吗

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

输出不会是这样的:

Take next student id 1001

constructing Student Chester

Take next student id 1002

constructing Student Trude

Press any key to continue . . .

希望你得到我想说的话

谢谢

卢克

解决方法

它是后增量运算符:它首先读取值(并将其赋值给变量),然后才增加它.

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

value = ++nextStudentId;

这会有你期望的行为.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读