在android中将引用作为参数传递 [英] passing reference as parameter in android
本文介绍了在android中将引用作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 java/android 的新手.我是一名 c/c++ 开发人员.我可以知道如何在android中将引用作为参数传递吗?一个说明性的 c 示例代码如下所示
I am newbie in java/android. I am a c/c++ developer. May i know how to pass a reference as parameter in android. An illustrative c sample code shown below
void main()
{
int no1 = 3, no2 = 2, sum = 0;
findsum( no1, no2, sum );
printf("sum=%d", sum );
}
void findsum( int no1, int no2, int& sum )
{
sum = no1 + no2;
}
请给我一个解决方案
谢谢
推荐答案
在 Java 中不能将 int 作为引用传递.int
是主要类型,只能按值传递.
You cannot pass an int as reference in Java. int
is a primary type, it can be passed only by value.
如果你仍然需要传递一个 int 变量作为引用,你可以将它包装在一个可变类中,例如一个 int 数组:
If you still need to pass an int variable as reference you can wrap it in a mutable class, for example an int array:
void findsum( int no1, int no2, int[] sum )
{
sum[0] = no1 + no2;
}
无论如何,我强烈建议你重构你的代码以更加面向对象,例如:
Anyway, I strongly suggest you to refactor your code to be more object oriented, for example:
class SumOperation {
private int value;
public SumOperation(int no1, int no2) {
this.value = no1 + no2;
}
public int getReturnValue() { return this.value; }
}
这篇关于在android中将引用作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文