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

标签 java c++ pass-by-reference call-by-value

我不确定这个主题是否与 Call-By-Reference 有关,但我对这两个片段有疑问:

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++ 中,它只是范围内的拷贝。 具体有什么区别?

最佳答案

如上所述,这里的主要问题是默认情况下,参数作为值而不是引用传递。在 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,它的内存地址完全是原始的内存地址,这是一个true 通过引用传递。

为了编辑这样的对象,您需要通过指针或通过引用传递它(通常,只要可能,通过引用传递优于指针)。

关于Java 与 C++(按引用调用?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60709437/

相关文章:

java - 我们可以在java swing中编辑生成的代码吗?

java - 如何获取另一个jar中的资源

c++ - ZLib.lib(d000062.o) : warning LNK4078: multiple '.text' sections found with different attributes

c++ - 帮助使用 OSSpinLock* 替换 while(true) {sleep(1);}

c - 将指针传递给函数不是在 C 中通过引用传递吗?

java - 将数据存储在Lucene或数据库中

java - Windows 的 Java GUI 编程?

c++ - Qt 对象管理与 Qt 插件

ios - SplitViewController引用逻辑

c++ - 在 C++ 中通过引用传递时 *val 和 &val 有何不同