Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ &引用;foo(int*指针)";vs.“;foo(int*指针)"; >和引用>强>(&)工作> < /P>_C++_Pointers - Fatal编程技术网

C++ &引用;foo(int*指针)";vs.“;foo(int*指针)"; >和引用>强>(&)工作> < /P>

C++ &引用;foo(int*指针)";vs.“;foo(int*指针)"; >和引用>强>(&)工作> < /P>,c++,pointers,C++,Pointers,在以下代码中: #include <iostream> using namespace std; void test1(int* pointer) { int foo = 2; pointer = &foo; } void test2(int* &pointer) { int foo = 3; pointer = &foo; } int main() { int aux = 1; int* p = &am

在以下代码中:

#include <iostream>
using namespace std;


void test1(int* pointer)
{
    int foo = 2;
    pointer = &foo;
}

void test2(int* &pointer)
{
    int foo = 3;
    pointer = &foo;
}

int main()
{
    int aux = 1;
    int* p = &aux;

    test1(p);
    cout << *p << ",";
    test2(p);
    cout << *p << endl;

    system("PAUSE");
}
#包括
使用名称空间std;
void test1(int*指针)
{
int-foo=2;
指针=&foo;
}
void test2(int*&指针)
{
int-foo=3;
指针=&foo;
}
int main()
{
int aux=1;
int*p=&aux;
试验1(p);

coutC++有两种将值传递给函数的通用方法-按值传递,如
voidfoo(inti)
和按引用传递,如
voidfoo(int&i)
。通过值传递创建传入值的副本,而通过引用传递将引用绑定到传入的值。因此,使用通过值传递的函数无法修改原始值,因为该函数只有副本,而通过引用传递提供了通过引用修改原始值的方法。

test1
的情况下,您所做的是按值传递指针类型的值。当您调用
test1(p)
时,就好像您这样做了:

int*指针=p;
int-foo=2;
指针=&foo;

因此,
p
保持不变

test2
的情况下,您通过引用传递指针类型的值,这确实会在
p
中产生变化。您实际上可以编写以下内容,并且具有相同的效果:

int*&pointer=p;
int-foo=3;
指针=&foo;


请注意,您通常不希望像在
test2
中所做的那样,获取像
foo
这样的局部变量的地址并将其分配给函数之外的某个对象。调用
test2(p)的结果
是指
p
指向一个不再存在的对象,因此任何试图读取
p
的行为都会产生所谓的“未定义行为”-基本上,计算机可能在执行
test2
期间重用了用于存储
foo
的内存,如果您尝试从
p

读取,您可能会得到一些非常奇怪的值C++有两种将值传递给函数的通用方法-传递值,如
void foo(int i)
,并通过引用传递,如
void foo(int&i)
。通过值传递创建传入值的副本,而通过引用传递将引用绑定到传入的值。因此,使用通过值传递的函数无法修改原始值,因为该函数只有副本,而通过引用传递提供了通过引用修改原始值的方法。

test1
的情况下,您所做的是按值传递指针类型的值。当您调用
test1(p)
时,就好像您这样做了:

int*指针=p;
int-foo=2;
指针=&foo;

因此,
p
保持不变

test2
的情况下,您通过引用传递指针类型的值,这确实会在
p
中产生变化。您实际上可以编写以下内容,并且具有相同的效果:

int*&pointer=p;
int-foo=3;
指针=&foo;


请注意,您通常不希望像在
test2
中所做的那样,获取像
foo
这样的局部变量的地址并将其分配给函数之外的某个对象。调用
test2(p)的结果
是指
p
指向一个不再存在的对象,因此任何试图读取
p
的行为都会产生所谓的“未定义行为”-基本上,在执行
test2
期间,计算机可能重新使用了用于存储
foo
的内存,如果您尝试从
p
读取
test1
test2
都有一个错误,它们会获取函数局部变量的地址,而h不在范围内,因此它们会悬空pointers@CoryKramer:实际上,
test1
不会创建悬空指针,因为它不会返回指向局部变量的指针。@CoryKramer将
int*pointer
更改为新创建的对象的正确方法是什么?在
test1()之后
p
仍然指向
aux
,因为您传递了一个副本(按值)@JohnnyMopp所以为了修改
p
,我需要传递一个指向指针的指针。
test1
test2
都有一个bug,它们使用的是一个函数局部变量的地址,该变量不在范围内,因此它们被挂起pointers@CoryKramer:实际上,
test1
不会创建悬挂指针,因为它不会返回指向局部变量的指针。@CoryKramer将
int*pointer
更改为新创建的对象的正确方法是什么?在
test1()
之后,
p
仍然指向
aux
,因为您传递了一个副本(按值)@johnnymop所以为了修改
p
,我需要传递一个指向指针的指针?