我是 java/android 的新手。我是一名 C/C++ 开发人员。我可以知道如何在 android 中将引用作为参数传递吗?下面显示了一个说明性的 c 示例代码
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
是一个基本类型,它只能按值传递。
如果您仍然需要传递一个 int 变量作为引用,您可以将它包装在一个可变类中,例如一个 int 数组:
void findsum( int no1, int no2, int[] sum )
{
sum[0] = no1 + no2;
}
无论如何,我强烈建议您重构您的代码以更加面向对象,例如:
class SumOperation {
private int value;
public SumOperation(int no1, int no2) {
this.value = no1 + no2;
}
public int getReturnValue() { return this.value; }
}
关于java - 在android中将引用作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9324106/