2016-12-01 62 views
1

我有一个任务。我需要将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中没有结构。

+0

'int a []'与'int * a'相同,所以参数作为指针传递。 'a [0] ++'递增指向的对象,而不是本地副本。 –

+0

另请注意,C++中类和结构之间的唯一区别是其成员的默认访问。 –

+0

结构与Class相同。唯一的区别是struct中的所有属性和方法总是默认为public。一个[0] ++是全局递增的,因为你传递一个指针数组而不是数组的副本。为了理解这一点,你可以学习谷歌指针的数组。 –

回答

3

差异:

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++ pass-by-copy或将其克隆到函数内部。


修复了在C++ int a[]第三输出

作为指针被传递,因此,原来的值被改变,但在PHP它是由值来传递,这是不变的外部。

对于它的简单修复将是&$a而不是$a函数参数。

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

0

请帮助在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