簡體   English   中英

這段代碼是如何工作的?

[英]How does this code work?

我正在尋找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;
}

這是輸出

下一個學生身份1000

建立學生切斯特

下一個學生ID 1001

建立學生特魯德

按任意鍵繼續 。

我很難理解為什么第一個學生ID是1000,如果值加一個然后將其打印出來

這有道理嗎

在studentId的構造函數中,兩行代碼接受nextStudentId並添加一行然后將其打印出來

輸出不會是這樣的:

下一個學生ID 1001

建立學生切斯特

下一個學生ID 1002

建立學生特魯德

按任意鍵繼續 。

希望你得到我想說的話

謝謝

盧克

該++是 -Increment操作者:它首先讀取值(並將其分配給一個變量), 才把它遞增。

將此與pre -increment運算符進行對比:

value = ++nextStudentId;

這會有你期望的行為。

請查看此問題以獲取更多信息: C ++中的增量 - 何時使用x ++或++ x?

value = nextStudentId++;

這使用了所謂的后增量運算符。 這樣做nextStudentId++將首先使用的當前值nextStudentIdvalue之后加一。 所以第一次, value將為1000, nextStudentId將立即成為1001,依此類推。

如果您改為:

value = ++nextStudentId;

這是預增量運算符,您將看到之前的預期。

在C和C ++中,增量(和減量)運算符以兩種形式出現

  1. prefix - ++ Object
  2. sufix - 對象++

前綴形式遞增然后返回值,但是后綴形式獲取值的快照,遞增對象然后返回先前拍攝的快照。

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

請注意第二個運算符有一個偽int參數,這是為了確保這些運算符的不同簽名。

您可以覆蓋這些運算符,但它確保在重寫的實現中維護語義以避免混淆。

嘗試這個

value = ++nextStudentId;

你知道運算符“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”首先遞增x,然后返回遞增的值

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM