我有一个任务。我需要将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] ++是全局递增的,因为你传递一个指针数组而不是数组的副本。为了理解这一点,你可以学习谷歌指针的数组。 –