需要将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 结构中的工作原理以及为什么[0] 全球增量。请帮助在PHP上重写此代码。我也知道,PHP中没有结构。
:
之间的差异function f($st, $r_st, $a, $n)
void f(Structure st, Structure& r_st, int a[], int n)
在C 中,您始终指定,按值或引用通过,但是在PHP中有一些预定义的规则。
修复了第1个输出
c 部分: st
是按值和原始值传递的,您通过此处通过的原始值不会更改。r_st
通过引用传递,然后更改原始值。
php部分:两个参数都是通过引用传递的,因为它们是类。
简单的修复程序是克隆对象st
并将其传递给函数到模仿C 通过逐副复制,或在功能中克隆它。
修复了第三次输出
在C int a[]
中以指针的形式传递,因此,原始值已更改,但是在PHP中,它按值传递,并且在外部不变。
简单的修复程序将是 &$a
而不是 $a
在功能参数中。
ps。我是C 开发人员,因此,PHP部分在术语中可能不准确。
您传递的ss0
和ss1
变量是该功能的对象访问者。请参阅对象和参考
传递的变量是按值。参见参考
请帮助在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
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- 在 C++ 中用派生类型重写成员函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 方法重写线程C++中的概念
- 为重写std::exception的库生成swig接口时出错
- 如何强制从重写方法调用重写的方法基方法?
- 用于C++的静态二进制检测或二进制重写工具和框架
- 如何将 if else 语句重写为 switch 语句
- 如何重写全局方法名称以在调用原始方法之前将我的代码推到前面
- 用 C 重写C++类
- 是否总是可以将使用递归编写的程序重写为不使用递归的程序C++,性能观点是什么?
- 重写虚拟函数和继承
- 将加密消息从 php 发送到 C++ 应用程序,然后使用 CryptoPP 进行解密
- C++调用使用重写函数的父类函数
- 重写打印函数而不是覆盖基类
- 不允许在类定义之外重写
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- C++:从抽象类重写纯虚拟运算符重载
- 需要将C 代码重写为PHP