繁体   English   中英

需要将C ++代码重写为PHP

[英]Need to rewrite C++ code to 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 ++结构如何工作以及为什么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代替$a

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

您要传入的ss0ss1变量是该函数的对象访问器。 请参阅对象和引用

传入的变量是按值。 请参阅通过引用传递

请帮助在PHP上重写此代码。

像这样做

function f($st, $r_st, &$a, $n) {

     $st= clone $st; #clone to get a real copy, not a refer

     $st->x++;
     $r_st->x++;
     $a[0]++; #&$a to simulate  ia[] (use as reference)
     $n++;
}

阅读有关PHP中的引用的信息。 我不是C ++开发人员。

http://php.net/manual/en/language.oop5.cloning.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM