美文网首页
java引用 VS C++指针小结

java引用 VS C++指针小结

作者: 汪汪小增 | 来源:发表于2018-10-19 13:26 被阅读0次

java参数传参都是传引用,其实就是指针,但是java只能传递一级指针

public class Test
{
    public static void test(StringBuffer str)
    {
        str = new StringBuffer("world");
    }
    public static void main(String[] args)
    {   
        StringBuffer str = new StringBuffer("hello");
        System.out.println(str);  //hello
        test(str);
        System.out.println(str);  //hello
    }
}

比如上方,test(str);虽然把引用传过去了,但是在函数test里面
对str的操作使得str的方向发生了改变,但是这没有影响到main函数的str

总结
(1)java可以在test函数对main函数的str引用所指向的内存做出修改
(2)但是java没有办法在test函数对main函数的str引用变量本身做出修改(比如main函数str的指向)
但是如果使用C++语言的话,就可以做到(2)

public class Test
{
//public static void test(A* &str) 也许大家在C++的数据结构看到的大多是这种结构
//但是如果这样写就表明test函数是无法改变main函数里面的str指针的,因为用引用来接受参数
    public static void test(A* *str)
    {
        str = new A("world");
    }
    public static void main(String[] args)
    {   
        A* str = new A("hello");
        System.out.println(str);  //hello
        test(str);
        System.out.println(str);  //word
    }
}

到这里基本可以分清java引用和C++指针的一点常见区别了
如果还没明白的话就看第二个例子吧

import java.io.Console;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*; 
 
class People
{   
    public int age;  
    public static void Swap(People a1, People a2)
    {     
        People tem;   
        tem = a1;    
        a1 = a2;     
        a2 = tem; 
    }  
    public static void Change(People a1, People a2)
    {      
        a1.age = 250;  
        a2.age = 250;   
    }
}
public class Empty
{ 
    public static void main(String[]args)    
    {        
        People a1 = new People();    
        People a2 = new People();  
        a1.age = 1;  
        a2.age = 2;  
        
        //这里没能交换,看起来是按值传递       
        People.Swap(a1, a2);      
        System.out.printf("%d \t %d", a1.age, a2.age);             
        System.out.println();  
        
        //这里修改了变量,看起来是按引用传递        People.Change(a1, a2);    
        System.out.printf("%d \t %d", a1.age, a2.age); 
    }
}
clipboard.png

[引用]https://blog.csdn.net/jiangnan2014/article/details/22944075

相关文章

网友评论

      本文标题:java引用 VS C++指针小结

      本文链接:https://www.haomeiwen.com/subject/bauyzftx.html