您的位置:首页 > Web前端

Pass-by-reference in C++ and java

2015-02-27 02:33 597 查看
- pass-by-reference and pass-by-pointer in C++

Refer to this

Reference is An alias (an alternate name) for an object. In following sample(swap(int& x, int& y), x is a — not a pointer to a, nor a copy of a, but a itself. Anything you do to a gets done to a, and vice versa.

Use references when you can, and pointers when you have to. References are usually preferred over pointers whenever you don’t need “reseating”. This usually means that references are most useful in a class’s public interface. References typically appear on the skin of an object, and pointers on the inside.

sample code:

#include <iostream>
using namespace std;
void swap(int* x, int* y)
{
int z = *x;
*x=*y;
*y=z;
}
void swap(int& x, int& y)
{
int z = x;
x=y;
y=z;
}

int main()
{
int a = 45;
int b = 35;
cout<<"Before Swap\n";
cout<<"a="<<a<<" b="<<b<<"\n";

swap(&a,&b);
cout<<"After Swap with pass by pointer\n";
cout<<"a="<<a<<" b="<<b<<"\n";

swap(a,b);
cout<<"After Swap with pass by reference\n";
cout<<"a="<<a<<" b="<<b<<"\n";
}


Output:

Before Swap
a=45 b=35
After Swap with pass by pointer
a=35 b=45

After Swap with pass by reference
a=45 b=35


pass-by-value of the reference in java

Refer to this blog

Java is always pass-by-value. The difficult thing to understand is that Java passes objects as references and those references are passed by value. In other words, java is more like passing the const pointer of the object.

Sample 1:

public static void main( String[] args ){
Dog aDog = new Dog("Max");
foo(aDog);
if( aDog.getName().equals("Max") ){ //true
System.out.println( "Java passes by value." );
}else if( aDog.getName().equals("Fifi") ){
System.out.println( "Java passes by reference." );
}
}

public static void foo(Dog d) {
d.getName().equals("Max"); // true
d = new Dog("Fifi");
d.getName().equals("Fifi"); // true
}


In this example aDog.getName() will still return “Max”. The value aDog within main is not overwritten in the function foo with the Dog “Fifi” as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return “Fifi” after the call to foo.

Dog aDog = new Dog("Max");
foo(aDog);
aDog.getName().equals("Fifi"); // true

public void foo(Dog d) {
d.getName().equals("Max"); // true
d.setName("Fifi");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: