传递给方法时,结构不通过引用传递 [英] Struct is not passed by reference when passed to a method
本文介绍了传递给方法时,结构不通过引用传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
struct Data {
public int x;
}
void change_x(Data data) {
data.x = 123;
}
Data a = Data();
change_x(a);
print("%d", a.x); // 0
但是文档说:
当结构类型实例传递给方法时,不会进行复制.而是传递对实例的引用.
- 在 https://wiki.gnome.org/Projects/Vala/Manual/Types一个>
when a struct type instance is passed to a method, a copy is not made. Instead a reference to the instance is passed.
- in https://wiki.gnome.org/Projects/Vala/Manual/Types
怎么了?
推荐答案
我认为您所引用的引用文本要么已经过时,要么一开始就错了.
I think the quoted text you are refering to is either outdated or was wrong to begin with.
如果您希望通过引用传递它,则必须使用 ref
(或 out
)(因此得名 ref
).
You have to use ref
(or out
) if you want it to be passed by reference (hence the name ref
).
struct Data {
public int x;
}
void change_x (ref Data data) {
data.x = 123;
}
int main () {
Data a = Data ();
change_x (ref a);
print ("%d\n", a.x);
return 0;
}
这篇关于传递给方法时,结构不通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文