# c++引用和指针

## 指针和引用

#include "stdafx.h"
#include <iostream>
using namespace std;
//引用和指针的例子
int run_ref_point() {
int x = 10;
int* ptr = &x; // 指针
int& ref = x; // 引用

cout << "x = " << x << endl;//10
cout << "*ptr = " << *ptr << endl;//10
cout << "ref = " << ref << endl;//10

*ptr = 20;
cout << "x = " << x << endl;//20
cout << "*ptr = " << *ptr << endl;//20
cout << "ref = " << ref << endl;//20

ref = 30;
cout << "x = " << x << endl;//30
cout << "*ptr = " << *ptr << endl;//30
cout << "ref = " << ref << endl;//30

return 0;
}


## 修改变量的值

#include <iostream>
using namespace std;

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

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

int main() {
int x = 10, y = 20;
// 使用指针交换变量的值
swap(&x, &y);
cout << "x = " << x << ", y = " << y << endl;//x = 20, y = 10

// 使用引用交换变量的值
swap(x, y);
cout << "x = " << x << ", y = " << y << endl;//x = 10, y = 20
return 0;
}


## 前面加&变成指针类型

void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int run_ref_point2() {
int x = 10, y = 20;

// 使用指针交换变量的值
swap(&x, &y);
}


1. 取地址符：&符号可以用来获取一个变量的地址，例如int a = 10; int *p = &a;，这里的&符号就是取地址符，用来获取变量a的地址。

2. 引用符：&符号还可以用来定义引用类型，例如int a = 10; int &b = a;，这里的&符号就是引用符，用来定义一个名为b的引用，它引用了变量a。

int a = 10;
int *p = &a;  // 获取变量a的地址，并将其赋值给指针p


int a = 10;
int &b = a;  // 定义一个引用b，它引用了变量a


posted @ 2024-02-26 22:18  赵青青  阅读(69)  评论(0编辑  收藏  举报