进行一个C++的学(01-引用与指针

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. 指针

指针本身就是一个对象,允许对指针赋值和拷贝,而且在指针的生命周期内它可以先后指定几个不同的对象。

指针无须在定义时赋值。指针如果没有被初始化将拥有一个不确定的值。

指针的四种状态:

  1. 指向一个对象。
  2. 指向相邻对象所占空间的下一个位置。
  3. 空指针,意味着指针没有指向任何对象。
  4. 无效指针,也就是上述情况之外的其他值。
#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
	*/
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值