*&和**在C ++中的含义

我几次在函数声明中find这些符号,但我不知道它们的意思。

例:

void raccogli_dati(double **& V, double **p, int N) { int ultimo = 3; V = new double * [N/2]; for(int i=0; i < N/2; i++) { V[i] = new double[N/2], std :: clog << "digita " << N/2 - i << " valori per la parte superiore della matrice V: "; for(int j=i; j < N/2; j++) std :: cin >> V[i][j], p[ultimo++][0] = (V[i][j] /= sqrt(p[i][0]*p[j][0])); } for(int i=1; i < N/2; i++) for(int j=0; j < i; j++) V[i][j] = V[j][i]; } 

这是通过引用的参数。 因此,在第一种情况下,您通过引用来获取指针参数,因此无论您对指针的值所做的任何修改都会反映到该函数之外。 其次是类似于第一个,唯一的区别是它是一个双指针。 看到这个例子:

 void pass_by_value(int* p) { //Allocate memory for int and store the address in p p = new int; } void pass_by_reference(int*& p) { p = new int; } int main() { int* p1 = NULL; int* p2 = NULL; pass_by_value(p1); //p1 will still be NULL after this call pass_by_reference(p2); //p2 's value is changed to point to the newly allocate memory return 0; } 

首先是对一个指针的引用,其次是对一个指针的引用。 另请参阅指针和引用不同的常见问题。

 void foo(int*& x, int**& y) { // modifying x or y here will modify a or b in main } int main() { int val = 42; int *a = &val; int **b = &a; foo(a, b); return 0; } 

这是通过引用传递的指针,而不是价值。 这例如允许改变函数中的指针(而不是指向的对象),使得调用代码看到改变。

比较:

 void nochange( int* pointer ) //passed by value { pointer++; // change will be discarded once function returns } void change( int*& pointer ) //passed by reference { pointer++; // change will persist when function returns } 

int*是一个指向int的指针。 然后int*&必须是一个指向int的指针。 同样, int**是一个指向int**的指针,那么int **&必须是指向指向int的指针的引用。

为了理解这些短语,我们来看看几件事情:

 typedef double Foo; void fooFunc(Foo &_bar){ ... } 

所以这是通过参考双倍。

 typedef double* Foo; void fooFunc(Foo &_bar){ ... } 

现在它传递一个指向double的指针。

 typedef double** Foo; void fooFunc(Foo &_bar){ ... } 

最后,它传递一个指向double引用的指针。 如果你用这样的typedef来思考,你会明白&和*的正确顺序以及它的含义。

*&表示通过引用接收指针。 这意味着它是传递参数的别名。 所以,它会影响传递的参数。

 #include <iostream> using namespace std; void foo(int *ptr) { ptr = new int(50); // Modifying the pointer to point to a different location cout << "In foo:\t" << *ptr << "\n"; delete ptr ; } void bar(int *& ptr) { ptr = new int(80); // Modifying the pointer to point to a different location cout << "In bar:\t" << *ptr << "\n"; // Deleting the pointer will result the actual passed parameter dangling } int main() { int temp = 100 ; int *p = &temp ; cout << "Before foo:\t" << *p << "\n"; foo(p) ; cout << "After foo:\t" << *p << "\n"; cout << "Before bar:\t" << *p << "\n"; bar(p) ; cout << "After bar:\t" << *p << "\n"; delete p; return 0; } 

输出:

 Before foo: 100 In foo: 50 After foo: 100 Before bar: 100 In bar: 80 After bar: 80