C ++通过引用传递还是通过值传递?

问题描述 投票:-1回答:2

所以我认为C ++按值工作,除非您使用指针。

尽管今天我编写了这段代码,其工作方式与预期不同:

#include <iostream>

using namespace std;

void bubbleSort(int A[],int arrSize);

bool binarySearch(int B[],int key,int arrSize2);

int main(){
    int numberArr[10] = {7,5,3,9,12,34,24,55,99,77};
    bool found;
    int key;


    bubbleSort(numberArr,10);
    /**
    uncomment this piece of code
        for(int i=0; i<10; i++){
        cout<<numberArr[i]<<endl;       
    }

    **/


    cout<<"Give me the key: ";
    cin>>key;

    found=binarySearch(numberArr,key,10);

    cout<<found;
}

void bubbleSort(int A[],int arrSize){
    int temp;

        for(int i=0; i<arrSize-1; i++){
        for(int j=i+1; j<10; j++){
            if(A[i]>A[j]){
                temp=A[i];
                A[i]=A[j];
                A[j]=temp;
            }
        }
    }
}



bool binarySearch(int B[],int key,int arrSize2){
    int i=0;
    bool found=false;

    while(i<arrSize2 && !found){
    if(B[i]==key)
    found=true;
    i++;
    }


    return found;
}

运行此命令时,numberArr中的值似乎也在main()函数中更改(排序),只需取消注释注释的块。

关于numberArr函数中main的值为什么也改变的任何想法?

c++ pass-by-reference pass-by-value
2个回答
2
投票
由于int[]

array decaying作为类型基本上仍然是指针。因此,您传递的是数组“引用”(如将用于“传递引用”的值,而不是像int&这样的实际C ++引用),而不是“值”。

int[]int*本身的“值”仍然是“传递值”,只是该值正被用于通过引用访问“指向”对象的内存。


1
投票

在C ++中,您不能按值传递数组。

© www.soinside.com 2019 - 2024. All rights reserved.