.h
文件用来声明函数
.cpp
文件用来函数实现
例如:如何交换a和b的值
sawp.h
void swap(int a, int b);
sawp.cpp
#include <iostream>
#include "swap.h"
using namespace std;
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
cout << "a:" << a << endl;
cout << "b:" << b << endl;
}
mian.cpp
// 导入swap.h函数文件
#include "swap.h"
using namespace std;
int main() {
int a = 10;
int b = 20;
// 调用明函数
swap(a, b);
return 0;
}
结构体: struct 结构体名 { 结构体成员列表 };
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
int score;
};
通过结构体创建变量的方式
#include <iostream>
using namespace std;
int main() {
// 可以省略 struct
struct Student student;
student.name = "小张";
student.age = 21;
cout << "姓名:" << student.name << ",年龄:" << student.age << endl;
}
#include <iostream>
using namespace std;
int main() {
// 可以省略 struct
struct Student student{"小张", 21};
cout << "姓名:" << student.name << ",年龄:" << student.age << endl;
}
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
int score;
} student;
int main() {
student.name = "小张";
student.age = 21;
cout << "姓名:" << student.name << ",年龄:" << student.age << endl;
}
指针结构体
#include <iostream>
using namespace std;
int main() {
Student student;
struct Student *p = &student;
p->name = "小张";
p->age = 21;
cout << "姓名:" << p->name << ",年龄:" << p->age << endl;
}