2016-12-01 63 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