#include <iostream>
using namespace std;
// 指针示例
void pointerExample() {
int a = 10;
int* p = &a; // p 是指向 int 类型的指针,&a 获取变量 a 的地址
cout << "Value of a: " << a << endl;
cout << "Address of a: " << &a << endl;
cout << "Value of p (address of a): " << p << endl;
cout << "Value at address p (value of a): " << *p << endl;
}
// 引用示例
void referenceExample() {
int b = 20;
int& r = b; // r 是 b 的引用,相当于别名
cout << "Value of b: " << b << endl;
cout << "Value of r (alias of b): " << r << endl;
r = 30; // 修改引用 r 实际上是修改了 b 的值
cout << "After modifying r, value of b: " << b << endl;
}
int main() {
pointerExample();
cout << "-------------------" << endl;
referenceExample();
return 0;
}
*指针 (`int p`)**:
&
可以获取变量的地址,使用 *
可以解引用指针,访问指针所指向的变量的值。引用 (int& r
):
通过这两个例子可以清楚地看到指针和引用的区别:指针是通过地址来间接访问变量,而引用则是直接作为变量的别名。
上一篇:c++常量
下一篇:c++求字符串长度
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站