Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.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++ *和*&;之间有什么区别;在C++;?_C++ - Fatal编程技术网

C++ *和*&;之间有什么区别;在C++;?

C++ *和*&;之间有什么区别;在C++;?,c++,C++,函数参数中的*和*&之间有什么区别。比如说, 这有什么区别, void a(SomeType *s) { } 而这个, void a(SomeType *&s) { } 将引用(使用&)传递到函数中时,可以修改该值,修改不会是本地的。如果未传递引用(无&),则修改将是函数的局部修改 #include <cstdio> int one = 1, two = 2; // x is a pointer passed *by value*, so changes are l

函数参数中的*和*&之间有什么区别。比如说,

这有什么区别,

void a(SomeType *s)
{

}
而这个,

void a(SomeType *&s)
{

}
将引用(使用
&
)传递到函数中时,可以修改该值,修改不会是本地的。如果未传递引用(无
&
),则修改将是函数的局部修改

#include <cstdio>
int one = 1, two = 2;

// x is a pointer passed *by value*, so changes are local
void f1(int *x) { x = &two; }

// x is a pointer passed *by reference*, so changes are propagated
void f2(int *&x) { x = &two; }

int main()
{
    int *ptr = &one;
    std::printf("*ptr = %d\n", *ptr);
    f1(ptr);
    std::printf("*ptr = %d\n", *ptr);
    f2(ptr);
    std::printf("*ptr = %d\n", *ptr);
    return 0;
}
#包括
int一=1,二=2;
//x是通过值*传递的指针,因此更改是本地的
void f1(int*x){x=&two;}
//x是通过引用*传递的指针,因此会传播更改
void f2(int*&x){x=&two;}
int main()
{
int*ptr=&one;
std::printf(“*ptr=%d\n”,*ptr);
f1(ptr);
std::printf(“*ptr=%d\n”,*ptr);
f2(ptr);
std::printf(“*ptr=%d\n”,*ptr);
返回0;
}
输出:

*ptr = 1 *ptr = 1 *ptr = 2 *ptr=1 *ptr=1 *ptr=2 首先,让我们在
a
中添加一些“肉”:

void a1(SomeType *s)
{
    s = new SomeType;
}

void a2(SomeType *&s)
{
    s = new SomeType;
}
void func()
{
    SomeType *p1 = nullptr;
    a1(p1);
    if (p == nullptr)
        std::cout << "p1 is null" << std::endl;
    else
        std::cout << "p1 is not null" << std::endl;

    SomeType *p2 = nullptr;
    a2(p2);
    if (p == nullptr)
        std::cout << "p2 is null" << std::endl;
    else
        std::cout << "p2 is not null" << std::endl;
}
现在假设您有这个代码,它调用
a

void a1(SomeType *s)
{
    s = new SomeType;
}

void a2(SomeType *&s)
{
    s = new SomeType;
}
void func()
{
    SomeType *p1 = nullptr;
    a1(p1);
    if (p == nullptr)
        std::cout << "p1 is null" << std::endl;
    else
        std::cout << "p1 is not null" << std::endl;

    SomeType *p2 = nullptr;
    a2(p2);
    if (p == nullptr)
        std::cout << "p2 is null" << std::endl;
    else
        std::cout << "p2 is not null" << std::endl;
}
void func()
{
SomeType*p1=nullptr;
a1(p1);
如果(p==nullptr)

std::cout在第一种情况下,函数接受指针的值。在第二种情况下,函数接受指针变量的非常量引用,这意味着您可以通过引用更改此指针位置。

int
和int&之间的区别是什么?
void a(SomeType*s)
:通过值传递指针
s
void a(SomeType*&s)
:通过引用传递指针
s
。@chris:我应该在哪里使用*和*&?@user3335,决定与
int
vs
int&
相同。