2012-04-30 11 views
1

だから私は、ポインタの合理的な理解を持っているが、私はこれらの違いが何であるかを尋ねた:C++概念ヘルプ、ポインタ

void print(int* &pointer) 

void print(int* pointer) 

私はまだ学生の私とイムない100%です。私のgoogleスキルは私に失敗しました。とにかくこのコンセプトをもう少し良く理解できるようになりますか?私は長い間、C++を使っていませんでした。私は学生を教えることを手伝っています。彼女の概念知識を固めようとしています。

答えて

5

最初にポインタを参照渡しし、2番目のポインタを値渡しします。

最初の署名を使用する場合は、ポインタが指しているメモリとそれが指しているメモリの両方を変更できます。例えば

void printR(int*& pointer) //by reference 
{ 
    *pointer = 5; 
    pointer = NULL; 
} 
void printV(int* pointer) //by value 
{ 
    *pointer = 3; 
    pointer = NULL; 
} 

int* x = new int(4); 
int* y = x; 

printV(x); 
//the pointer is passed by value 
//the pointer itself cannot be changed 
//the value it points to is changed from 4 to 3 
assert (*x == 3); 
assert (x != NULL); 

printR(x); 
//here, we pass it by reference 
//the pointer is changed - now is NULL 
//also the original value is changed, from 3 to 5 
assert (x == NULL); // x is now NULL 
assert (*y = 5 ;) 
0

最初に参照によってポインタを渡します。 参照渡しの場合、関数は渡された引数の値を変更できます。

void print(int* &pointer) 
{ 
    print(*i); // prints the value at i 
    move_next(i); // changes the value of i. i points to another int now 
} 

void f() 
{ 
    int* i = init_pointer(); 
    while(i) 
    print(i); // prints the value of *i, and moves i to the next int. 
}