开发者社区> 问答> 正文

Java与C ++(按引用调用?)

我不确定本主题是否与“按次致电参考”有关,但是我对以下两个片段有疑问:

java:

public static int calculateWinner(int[][] game){
        game[0][0] = 5; 
.
.
.
}


public static void main(String[] args) {

        int[][] game = {
            {1, 2, 2},
            {2, 1, 2},
            {1, 1, 1}
        };

        int winner = calculateWinner(game);
.
.
.
}

c++:

int calculateWinner(array<array<int, 3>, 3> field) {
    field[0][0] = 5;
.
.
.
}

int main(int argc, const char* argv[]) {

    array<array<int, 3>, 3> field;
    field[0] = { 2, 0, 1 };
    field[1] = { 0, 1, 0 };
    field[2] = { 1, 0, 2 };

    int winner = calculateWinner(field);
.
.
.
}

因此,如果我在main方法中打印出数组,为什么在Java中位置[0] [0]的数组为5,而在C ++中不是?我了解到,在C ++中,它只是作用域中的一个副本。到底有什么区别?

问题来源:Stack Overflow

展开
收起
montos 2020-03-22 12:27:42 654 0
1 条回答
写回答
取消 提交回答
  • 如上所述,这里的主要问题是默认情况下,参数作为值而不是引用传递。在Java中也是如此,但是,在Java片段中传递的是指向数组的指针,而不是指向数组本身的指针,这使其看起来像是“按引用传递”,但是,Java始终按值传递!

    在C ++中,可以按值和按引用传递。您可以将指针传递到对象,该对象是程序存储器中的新节,其中包含所需值的位置,也可以将引用传递到存储值的内存中的特定位置。在以下代码片段中注意指针的内存地址:

    #include <iostream>
    
    void foo(int num)
    {
        std::cout << "The location of pass-by-value num is: " << &num << std::endl;
    }
    
    void foo1(int* num)
    {
        std::cout << "The location of num* is: " << &num << " But its value is :" << num << std::endl;
    }
    
    void foo2(int& num)
    {
        std::cout << "The location of num& is: " << &num << std::endl;
    }
    
    int main()
    {
        int num;
    
        std::cout << "The location of num is: " << &num << std::endl;
    
        foo(num);
        foo1(&num);
        foo2(num);
    }
    

    该代码段的输出为:

    The location of num is: 0x7ffce8cceccc
    
    The location of pass-by-value num is: 0x7ffce8ccecac
    
    The location of num* is: 0x7ffce8cceca8 But its value is :0x7ffce8cceccc
    
    The location of num& is: 0x7ffce8cceccc
    

    在foo中,我们传递整数的值,因此,获得的地址与原始地址不同。

    在foo1中,我们将指针的值传递给num。指针具有其自己的内存位置,其值是num的内存地址。

    在foo2中,我们将引用传递给整数num,它的内存地址正好是原始内存的内存地址,这是一个真正的按引用传递。

    为了编辑这样的对象,您需要按指针或按引用传递它(通常,尽可能通过指针传递按引用而不是指针)。

    回答来源:Stack Overflow

    2020-03-22 12:28:38
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载