gpt4 book ai didi

c++ - 引用 C++ 中的指针交换

转载 作者:搜寻专家 更新时间:2023-10-31 01:00:17 25 4
gpt4 key购买 nike

谁能告诉我我的理解是否正确?有人可以告诉我下面的代码是否用于引用指针吗?

# include <iostream>
using namespace std;

//function swaps references,
//takes reference to int as input args and swap them
void swap(int& a, int& b)
{
int c=a;
a=b;
b=c;
}

int main(void)
{
int i=5,j=7;

cout<<"Before swap"<<endl;
cout<<"I:"<<i<<"J:"<<j<<endl;
swap(i,j);
cout<<"After swap"<<endl;
cout<<"I:"<<i<<"J:"<<j<<endl;
return 0;

}

最佳答案

您可以像这样创建对指针的引用。

int i, j;        
int* ptr_i = &i; //ptr_i hold a reference to a pointer
int* ptr_j = &j;
swap(ptr_i, ptr_j);

功能应该是,

void swap(int*& a, int*& b)
{
//swap
int *temp = a;
a = b;
b = temp;
}

注意:

  • a 是指针的引用,在上例中是 ptr_i。

  • *a 取消引用 ptr_i 指向的内容,所以你得到变量 the指针,ptr_i 指向。

有关更多信息,请参阅 this .

关于c++ - 引用 C++ 中的指针交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31419353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com