void SomeFun1(int *);
void SomeFun2(int **);
int i;
int *ptr = &i;
//when you want value of ptr should remain unchanged, but you want to change only value of i, use,
SomeFun1(int *)
//when you want value of ptr should change. i.e, it should point to some other memory other than i, use,
SomeFun2(int **);
在C++中,您可以通过引用传递参数,当您希望对参数进行修改并影响调用者传递的参数时,就需要这样做。也就是说,通过引用传递表示输出或输入/输出参数。
如果函数需要指针(显然),或者您想要表示可选的输出参数-因为引用必须始终绑定到某个东西,但指针可以为null,则应传递指针。
按照同样的逻辑,如果函数实际上需要双重指针(在C ++中非常罕见),或者如果您想要表示指针类型的可选[输入]输出参数(也很少见),则传递指针指针。
下面是一些示例(虽然构造的,但应该能够说明问题):
int square(int x) //pass int by value
{ return x * x; }
void squareRoots(double in, double &plus, double &minus) //pass double by reference
{
plus = sqrt(in);
minus = -plus;
}
int toNumber(String s, bool *ok = nullptr) //optional out parameter
{
try {
int val = s.toNumber();
if (ok)
*ok = true;
return val;
} catch (NotANumber &) {
if (ok)
*ok = false;
return 0;
}
}
int computeAge(Person *person) //pass pointer by value
{
if (!person)
return -1;
else
return now() - person->dateOfBirth();
}
bool createPerson(Person * &person) //pass pointer by reference
{
if (tooManyPeople())
return false;
person = new Person();
return true;
}
int sum(int **values) //pass double pointer by value
{
if (!values)
return 0;
int res = 0;
while (*values) {
res += **values;
++values;
}
return res;
}
bool allocate(int ** &arr) //pass double pointer by reference
{
if (!enoughMemory())
return false;
arr = new int*[1024]; // array of 1024 pointers to int
return true;
}
bool newNode(Node **node = nullptr) //optional out parameter
{
Node *added = dataStructure.createNode();
if (node)
*node = added;
return added;
}
在C中,双指针更常见,因为C没有引用类型。因此,你也使用指针来“按引用传递”。在上面的C++示例中,&
在参数类型中使用时,C中会使用*
(并在操作参数时对其进行解引用)。以下是一个示例:
void squareRoots(double in, double *plus, double *minus) //pass double "by reference"
{
*plus = sqrt(in);
*minus = -*plus;
}
<type>**
。例子:
int main(int argc, char **argv) { // argv is an array of char*
int alloc_my_object(my_object **ob1)
。基本上,如果您有一个需要更改的参数,则将其作为指针传递进去。如果参数类型已经是指针,则会传入“指向指针”的指针。 - amdixonC++
和C
。两者在这方面有很大的区别;您真的希望获得关于两者的答案吗? - Angew is no longer proud of SO