1. 引用
引用并非对象,相反的,它只是为一个已存在的对象所起的另外一个名字。
对引用的修改也会作用于引用绑定的对象
#include<iostream>
using namespace std;
int main() {
// 创建一个变量i的引用 iReference
//int i = 12;
//int& iReference = i;
int i = 12, & iReference = i;
cout << "value of i: " << i << endl;
cout << "value of iReference: " << iReference << endl;
/*
输出结果为
value of i : 12
value of iReference : 12
*/
iReference = 11;
cout << "value of i: " << i << endl;
cout << "value of iReference: " << iReference << endl;
/*
输出结果为
value of i : 11
value of iReference : 11
*/
}
2. 指针
指针本身就是一个对象,允许对指针赋值和拷贝,而且在指针的生命周期内它可以先后指定几个不同的对象。
指针无须在定义时赋值。指针如果没有被初始化将拥有一个不确定的值。
指针的四种状态:
- 指向一个对象。
- 指向相邻对象所占空间的下一个位置。
- 空指针,意味着指针没有指向任何对象。
- 无效指针,也就是上述情况之外的其他值。
#include<iostream>
using namespace std;
int main() {
// 定义一个指针
//int i = 12;
//int* i = &i;
int i = 12, * iP = &i;
cout << "the value of i: " << i << endl;
cout << "the value of iP: " << iP << endl;
cout << "the value of *ip: " << *iP << endl;
*iP = 11;
*iP = 11;
cout << "the value of i: " << i << endl;
cout << "the value of iP: " << iP << endl;
cout << "the value of *ip: " << *iP << endl;
/*
the value of i: 12
the value of iP: 00CFFAB4
the value of *ip: 12
the value of i: 11
the value of iP: 00CFFAB4
the value of *ip: 11
*/
}