int main(){ char x {}; // assume this is assigned memory address 140 char& ref { x }; // ref is an lvalue reference to x (when used with a type, & means lvalue reference) return 0;}
因为 ref 是 x 的别名,所以任何使用ref的地方,程序仍然会到内存地址140的地方去取值。编译器同样为我们代劳了寻址的过程,我们无需操心。
#include <iostream>int main(){ int x{ 5 }; std::cout << x << '\n'; // print the value of variable x std::cout << &x << '\n'; // print the memory address of variable x return 0;}
#include <iostream>int main(){ int x{ 5 }; std::cout << x << '\n'; // print the value of variable x std::cout << &x << '\n'; // print the memory address of variable x std::cout << *(&x) << '\n'; // print the value at the memory address of variable x (parentheses not required, but make it easier to read) return 0;}
int; // a normal intint&; // an lvalue reference to an int valueint*; // a pointer to an int value (holds the address of an integer value)
要创建指针变量,只需定义一个指针类型的变量:
int main(){ int x { 5 }; // normal variable int& ref { x }; // a reference to an integer (bound to x) int* ptr; // a pointer to an integer return 0;}
注意,这个星号是指针声明语法的一部分,而不是使用解引用操作符。
"最佳实践"
声明指针类型时,在类型名称旁边加上星号。
"注意"
尽管通常情况下我们不应该在一行定义多个变量,但是如果需要这么做,则每个指针变量前面都需要星号
int* ptr1, ptr2; // incorrect: ptr1 is a pointer to an int, but ptr2 is just a plain int!int* ptr3, * ptr4; // correct: ptr3 and p4 are both pointers to an int
int main(){ int i{ 5 }; double d{ 7.0 }; int* iPtr{ &i }; // ok: a pointer to an int can point to an int object int* iPtr2 { &d }; // not okay: a pointer to an int can't point to a double double* dPtr{ &d }; // ok: a pointer to a double can point to a double object double* dPtr2{ &i }; // not okay: a pointer to a double can't point to an int}
#include <iostream>int main(){ int x{ 5 }; int* ptr{ &x }; // initialize ptr with address of variable x std::cout << x << '\n'; // print x's value std::cout << *ptr << '\n'; // print the value at the address that ptr is holding (x's address) *ptr = 6; // The object at the address held by ptr (x) assigned value 6 (note that ptr is dereferenced here) std::cout << x << '\n'; std::cout << *ptr << '\n'; // print the value at the address that ptr is holding (x's address) return 0;}
输出结果:
5
5
6
6
在这个例子中,我们首先定义了指针ptr,它的初始化为变量x的地址,然后打印了 x 和 *ptr 的值(5)。因为*ptr 返回的是左值,所我们可以把它用在赋值号的左侧,这样就可以将ptr 所指的变量的值修改为 6。然后,再次打印 x 和 *ptr以便确定我们的修改是否生效。
#include <iostream>int main(){ int x{ 5 }; int& ref { x }; // get a reference to x int* ptr { &x }; // get a pointer to x std::cout << x; std::cout << ref; // use the reference to print x's value (5) std::cout << *ptr << '\n'; // use the pointer to print x's value (5) ref = 6; // use the reference to change the value of x std::cout << x; std::cout << ref; // use the reference to print x's value (6) std::cout << *ptr << '\n'; // use the pointer to print x's value (6) *ptr = 7; // use the pointer to change the value of x std::cout << x; std::cout << ref; // use the reference to print x's value (7) std::cout << *ptr << '\n'; // use the pointer to print x's value (7) return 0;}