我有一個任務。我需要將C++代碼重寫爲PHP。需要重寫C++代碼到PHP
#include <iostream>
using namespace std;
struct Structure {
int x;
};
void f(Structure st, Structure& r_st, int a[], int n) {
st.x++;
r_st.x++;
a[0]++;
n++;
}
int main(int argc, const char * argv[]) {
Structure ss0 = {0};
Structure ss1 = {1};
int ia[] = {0};
int m = 0;
f(ss0, ss1, ia, m);
cout << ss0.x << " "
<< ss1.x << " "
<< ia[0] << " "
<< m << endl;
return 0;
}
返回的編譯器是0 2 1 0
。我已經重寫了PHP的代碼是這樣的:
<?php
class Structure {
public function __construct($x) {
$this->x = $x;
}
public $x;
}
function f($st, $r_st, $a, $n) {
$st->x++;
$r_st->x++;
$a[0]++;
$n++;
}
$ss0 = new Structure(0);
$ss1 = new Structure(1);
$ia = [0];
$m = 0;
f($ss0, $ss1, $ia, $m);
echo $ss0->x . " "
. $ss1->x . " "
. $ia[0] . " "
. $m . "\n";
這段代碼的回報是:1 2 0 0
。我知道PHP,我知道它爲什麼返回這個值。我需要了解C++結構如何工作以及爲什麼全局遞增[0] ++。請幫助在PHP上重寫此代碼。我也知道在PHP中沒有結構。
'int a []'與'int * a'相同,所以參數作爲指針傳遞。 'a [0] ++'遞增指向的對象,而不是本地副本。 –
另請注意,C++中類和結構之間的唯一區別是其成員的默認訪問。 –
結構與Class相同。唯一的區別是struct中的所有屬性和方法總是默認爲public。一個[0] ++是全局遞增的,因爲你傳遞一個指針數組而不是數組的副本。爲了理解這一點,你可以學習谷歌指針的數組。 –