c++重点知识总结
只是为方便学习,不做其他用途,原作者为黑马程序
一、const与指针
const修饰指针有三种情况
- const修饰指针 — 常量指针
- const修饰常量 — 指针常量
- const即修饰指针,又修饰常量
int main() {int a = 10;int b = 10;//const修饰的是指针,指针指向可以改,指针指向的值不可以更改const int * p1 = &a; p1 = &b; //正确//*p1 = 100; 报错//const修饰的是常量,指针指向不可以改,指针指向的值可以更改int * const p2 = &a;//p2 = &b; //错误*p2 = 100; //正确//const既修饰指针又修饰常量const int * const p3 = &a;//p3 = &b; //错误//*p3 = 100; //错误system("pause");return 0;
}
//技巧:看const右侧紧跟着的是指针还是常量, 是指针就是常量指针,是常量就是指针常量
二、结构体指针
结构体指针可以通过 -> 操作符 来访问结构体中的成员
//结构体定义
struct student
{//成员列表string name; //姓名int age; //年龄int score; //分数
};int main() {struct student stu = { "张三",18,100, };struct student * p = &stu;p->score = 80; //指针通过 -> 操作符可以访问成员cout << "姓名:" << p->name << " 年龄:" << p->age << " 分数:" << p->score << endl;system("pause");return 0;
}//地址传递
void func(student *stu)
{stu->age = 28;cout << "子函数中 姓名:" << stu->name << " 年龄: " << stu->age << " 分数:" << stu->score << endl;
}main里面:func(&stu);//const使用场景
void printStudent(const student *stu) //加const防止函数体中的误操作
{//stu->age = 100; //操作失败,因为加了const修饰cout << "姓名:" << stu->name << " 年龄:" << stu->age << " 分数:" << stu->score << endl;}
三、.与->区别
c++中 . 和 -> 主要是用法上的不同
1、A.B则A为对象或者结构体;
2、A->B则A为指针,->是成员提取,A->B是提取A中的成员B,A只能是指向类、结构、联合的指针;
四、内存分区
C++程序在执行时,将内存大方向划分为4个区域
- 代码区:存放函数体的二进制代码,由操作系统进行管理的
- 全局区:存放全局变量和静态变量以及常量
- 栈区:由编译器自动分配释放, 存放函数的参数值,局部变量等
- 堆区:由程序员分配和释放,若程序员不释放,程序结束时由操作系统回收
C++中主要利用new在堆区开辟内存
堆区开辟的数据,由程序员手动开辟,手动释放,释放利用操作符 delete
利用new创建的数据,会返回该数据对应的类型的指针
示例:
int* func()//返回int指针的函数
{int* a = new int(10);return a;
}int main() {int *p = func();cout << *p << endl;//利用delete释放堆区数据delete p;//要记得释放!!//cout << *p << endl; //报错,释放的空间不可访问system("pause");return 0;
}
new的释放:
delete p;//p不是数组变量
delete[] p;//p是数组】
栈区的数据由编译器释放,因此函数中的局部变量不能作为地址或者引用返回
//错误示范1:
int * func()
{int a = 10;
//若是用static把局部变量变为静态变量,则可以用
//static int a =10;return &a;
}int main() {int *p = func();cout << *p << endl;system("pause");return 0;
}
//错误示范2:
/返回局部变量引用
int& test01() {int a = 10; //局部变量
//若是用static把局部变量变为静态变量,则可以用
//static int a =10;return a;
}
int main() {//不能返回局部变量的引用int& ref = test01();cout << "ref = " << ref << endl;
}
函数中局部变量能作为值返回
#include <iostream>
using namespace std;int test01() {int a = 10; //局部变量return a;
}
int main() {int ref = test01();cout << "ref = " << ref << endl;
}
五、引用
功能:给变量起别名
语法: 数据类型 &别名 = 原名
int main() {int a = 10;int &b = a;cout << "a = " << a << endl;cout << "b = " << b << endl;b = 100;cout << "a = " << a << endl;cout << "b = " << b << endl;system("pause");return 0;
}
- 引用必须初始化
- 引用在初始化后,不可以改变
int main() {int a = 10;int b = 20;//int &c; //错误,引用必须初始化int &c = a; //一旦初始化后,就不可以更改c = b; //这是赋值操作,不是更改引用cout << "a = " << a << endl;cout << "b = " << b << endl;cout << "c = " << c << endl;system("pause");return 0;
}
引用做函数参数,可以简化指针修改实参
//1. 值传递
void mySwap01(int a, int b) {int temp = a;a = b;