我有任务我需要将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++结构如何工作以及为什么a [0] ++会全局递增。请帮助在PHP上重写此代码。我也知道PHP中没有struct。

最佳答案

之间的区别:

function f($st, $r_st, $a, $n)
void f(Structure st, Structure& r_st, int a[], int n)

在C++中,您总是指定按值或引用传递,但在PHP中有一些预定义的规则。

修复了第一个输出

C++部分:st按值传递,并且您在此处传递的原始值不变。 r_st通过引用传递,并且原始值被更改。

PHP部分:这两个参数都是类,因此都通过引用传递。

简单的解决方法是克隆对象st并将其传递给函数以模仿C++传递副本,或将其克隆到函数内部。

修复了第三输出

在C++中,int a[]是作为指针传递的,因此,原始值已更改,但是在PHP中,它是通过值传递的,并且在外部未更改。

简单的解决方法是在函数参数中使用&$a而不是$a

PS。我是C++开发人员,因此,PHP部分的术语可能不准确。

07-24 09:46
查看更多