目录
散碎概念
1.指针和其他变量一样,都是要初始化的,否则,包含的值将是随机的垃圾值。
2.声明指针的方式。 (* 叫解除引用运算符)
int *pInteger =NULL;
*pInteger是pInteger对应的地址。
3.引用运算符或称地址运算符(&)获取变量的地址,如:
int Age = 30;
&Age是存储该变量的值(30)的内存的地址,换句话说,这是个地址。
3.符号(*)与符号(&)的关系
#include <iostream>
using namespace std;
int main()
{
int Age = 30;
int* pInteger = &Age;
int *oInteger = &Age;
cout << "Integer Age is at(pInteger): 0x: " << hex << pInteger << endl;
cout << "Integer Age is at(&Age): 0x: " << hex << &Age << endl;
cout << "Integer Age is at(*oInteger):0x: " << hex << oInteger << endl;
system("pause");
return 0;
}
输出:
所以,通过实验可以看出int* s = a1; &Age = a2;那么a1和a2其实都是地址,这点很重要或者说,&value和int* 类型所表达的式子都是地址变量。那*value表达的是声明呢?当然,表达的也是地址,并没有什么区别。
如果有合法的指针pData,要访问它包含的地址处存储的值,可使用*pData。同样,还是刚才的例子,当我用*pInteger十进制输出时,是30,符合原理。
#include <iostream>
using namespace std;
int main()
{
int Age = 30;
int* pInteger = &Age;
cout << "Integer Age is at(pInteger): 0x: " << hex << pInteger << endl;
cout << "Integer Age is at(&Age): 0x: " << hex << &Age << endl;
cout << "Integer Age is at(pInteger): 0x: " << dec << *pInteger << endl;
system("pause");
return 0;
}
出现了30,说明 *pInteger 等同于 Age。
动态内存分配
c++提供了两个运算符——new和delete,指针是包含内存地址的变量,在高效地动态分配内存方面扮演了重要角色。
使用new来分配新的内存块,成功的话,new将返回指向一个指针,指向分配的内存。但是,需要注意的是,使用new分配的内存块需要使用delete来释放。
Const 与指针
如下面这个例子:
#指针包含的地址可以修改;指针指向的变量也不能修改。
const double* x
#指针包含的地址是常量,不能修改;指针指向的变量能修改。
double* const x
#指针包含的地址是常量,不能修改;指针指向的变量也不能修改。
const double* const x
将指针传递给函数
下面的是将指针传递给函数。
#include <iostream>
using namespace std;
void CalcArea(const double* const pPi,
const double* const pRadius,
double* const pArea)
{
if (pPi && pRadius &&pArea)
*pArea = (*pPi) * (*pRadius) * (*pRadius);
}
int main()
{
const double Pi = 3.1415;
double Radius = 2;
double Area = 5;
CalcArea(&Pi, &Radius, &Area);
cout << "Area is = " << Area << endl;
system("pause");
return 0;
}
指针与数组的联系
数组变量就是指针,因此也可将用于指针的解除引用运算符(*)用于数组。同样,可将数组运算符([])用于指针。
使用指针时常犯的编程错误
内存泄漏:有new,没有配套的delete来释放内存。
指针指向无效的内存单元:无效的指针
悬浮指针:使用delete释放后,任何有效指针都将无效。解决:在初始化指针或释放指针后将其设置为NULL,并在使用运算符*对指针解除引用前检测它是否有效。
引用
引用是变量的别名。声明引用时,需要将其初始化为一个变量,因此引用只是另一种访问相应变量存储的数据的方式。要声明引用,需使用(&)符号。
PS:当引用为 int& 时,表引用; 当 &value时 , 表去地址符。
#include <iostream>
using namespace std;
int main()
{
int a1 = 30;
cout << "a1 is = " << a1 << endl;
cout << "a1 is at address: " << &a1 << endl;
cout << " " << endl;
int& Ref = a1;
cout << "Ref is = " << Ref << endl;
cout << "Ref is at address: " << &Ref << endl;
cout << " " << endl;
int& Ref2 = Ref;
cout << "Ref2 is = " << Ref2 << endl;
cout << "Ref2 is at address: " << &Ref2 << endl;
cout << " " << endl;
system("pause");
return 0;
}
输出:
按引用传递参数
引用优点:可避免将形参复制给形参,从而极大的提高性能。举例:
#include <iostream>
using namespace std;
void Cal(const int& N1, int& Res)
{
Res = N1 * N1;
}
int main()
{
int Number = 27;
int Square = 2;
Cal(Number, Square);
cout << Square << endl;
system("pause");
return 0;
}