How does this code work?

I am looking at C ++ for mannequins and found this code

#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;
}

this is a conclusion

Take the next student id 1000

student building chester

Take the following student ID 1001

building student work

Press any key to continue.,.

I find it very difficult to understand why the first student ID is 1000 if the value adds it to it and then prints it

it makes sense

right in the constructor for studentId take two lines of code nextStudentIdand add one to it, then print

Something like this will not be output:

Take the following student ID 1001

student building chester

Take the next student id 1002

building student work

Press any key to continue.,.

hope you get what I'm trying to say

thank

Luke

+3
source share
5

++ post-increment: ( ), .

pre-increment:

value = ++nextStudentId;

, .

: ++ - x ++ ++ x?

+9
value = nextStudentId++;

post-increment. nextStudentId++ nextStudentId value, . , , value 1000, nextStudentId 1001 ..

:

value = ++nextStudentId;

pre-increment, , .

+5

C ++ ( )

  • prefix - ++ Object
  • sufix - Object ++

, , , .

T& T::operator ++(); // This is for prefix
T& T::operator ++(int); // This is for suffix

, int, .

, , , .

+4

value = ++nextStudentId;
+1

, "x ++" "++ x"?

"x ++" x, x

:

int x = 1;
std::cout << x++ << std::endl; // "1" printed, now x is 2
std::cout << x << std::endl; // "2" printed

"++ x" first increments x and then returns an extra value

int y = 1;
std::cout << ++y << std::endl; // "2" printed, y is 2
std::cout << y << std::endl; // "2"
+1
source

Source: https://habr.com/ru/post/1777107/


All Articles