1.函数
返回值类型 函数名 (参数列表传入数据){
函数体语句
return表达式
}
#include <iostream>
using namespace std;
int add(int num1, int num2) {
int sum = num1 + num2;
return sum;
};
int main()
{
int a = 10;
int b = 20;
int c=add(a, b);
cout << c << endl;
}
.h为头文件,记录函数声明的地方
.cpp为源文件,记录函数实现内容的地方
2.指针:
指针的作用为,通过指针访问内存。
内存编号一般是从0开始记录的,一般用16进制表示
可以利用指针变量保存地址。
数据类型 * 变量名;
指针可以用来保存一个内存地址,指针就是一个地址
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int* p;
p = &a;//&为取地址符号
cout << p << endl;
}
通过指针修改内存值:
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int* p;
p = &a;//&为取地址符号
*p = 1000;//*为解引用符号,通过这个直接修改A的值
cout << a<< endl;
}
不管什么数据类型,指针在32位系统下的空间大小为4字节
在64位系统下为8个字节
空指针:
指针变量指向内存种编号为0的空间,用于初始化指针变量,空指针的内存是不可访问的。
int *p =null;
野指针:指针变量指向非法的内存空间
int *p=(int*)0*1100;
访问指针会报错
3.const修饰
const修饰的指针:常量指针 指针的指向可以改,指针指向的值不可以改
const int * p =&a;
const修饰的常量:指针常量 指针的指向不可以改,指针指向的值可以改
int * const p =&a;
const即修饰指针,又修饰常量 指针的指向和值都不可以改
const int * const p =&a;
通过指针访问数组:
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9 };
int* p = arr;//数组的名字就是第一个元素的首地址
cout << *p << endl;
*p++;
cout << *p << endl;//++后为指针向前挪了4个字节,int为4字节。即访问的是第二个元素。
}
3.结构体struct
结构体属于用户自定义的数据类型,允许用户存储不同的数据类型
语法:struct 结构体名{结构体成员列表};
3种方式创建:
struct 结构体名 变量名
struct 结构体名 变量名={值1,值2,值3.....}
定义结构体时顺便创建变量
#include <iostream>
using namespace std;
//自定义类型的集合
struct student {
int id;
string name;
int age;
int score;
};
int main()
{
//第一种方法:
struct student S1;
S1= { 001,"小明",18,644 };
cout << "S1号学生的年龄为:" << S1.age<< endl;
//第二种方法
struct student S2= { 002,"小红",19,620 };
cout << "S2号学生的分数为:" << S2.score << endl;//通过.来访问属性
}
struct关键字在C++里可以省略,定义时不行。
#include <iostream>
using namespace std;
//自定义类型的集合
struct student {
int id;
string name;
int age;
int score;
};
int main()
{
struct student arr[3] = {
{003,"张三",20,456},
{004,"李四",18,441},
{005,"王五",19,375},
};
cout << "005号学生的名字是:" << arr[2].name << endl;
}
结构体指针操作符->
通过结构体指针访问结构体属性
#include <iostream>
using namespace std;
//自定义类型的集合
struct student {
int id;
string name;
int age;
int score;
};
int main()
{
struct student arr[3] = {
{003,"张三",20,456},
{004,"李四",18,441},
{005,"王五",19,375},
};
cout << "005号学生的名字是:" << arr[2].name << endl;
student* p = arr;
cout << "003号学生的名字是:" << p->name << endl;
++p;
cout << "004号学生的名字是:" << p->name << endl;
}