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
vsint&
相同。