簡體   English   中英

C ++通過指針傳遞和通過引用傳遞

[英]C++ Passing by pointer and passing by reference

#include<iostream>

using namespace std;

class A{
        int *numbers[5];
        public:
            void assignment(int ** x){
                    for(int i=0;i<5;i++)
                            numbers[i]=x[i]; //not changing just the value of *numbers[i] but the pointer numbers[i]
            }
            void print(){
                    for(int i=0; i<5;i++)
                            cout<< *numbers[i]<<endl;
            }
};

int main(){
    int *x[5];
    for(int i; i<5;i++){
            x[i]= new int(i);
            cout<<*x[i]<<endl;
    }
    cout<<endl;
    A numbers;
    numbers.assignment(x);
    numbers.print();
    return 0;
}

我的問題很具體。 我想做與上述代碼相同的事情,但不是通過指針傳遞函數賦值(int **)的參數來通過引用來實現。 我該如何實現?

采用:

void assignment(int* (&x)[5]) ...

編輯:對於注釋“如果長度...不是標准長度...”,可以使用模板:

template<int N> void assignment(int* (&x)[N]) ...

編譯器將自動推斷N。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM