函数声明和使用

.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;
};

通过结构体创建变量的方式

  • struct 结构体名 变量名
#include <iostream>
using namespace std;

int main() {
    // 可以省略 struct
    struct Student student;
    student.name = "小张";
    student.age = 21;
    cout << "姓名:" << student.name << ",年龄:" << student.age << endl;
}
  • struct 结构体名 变量名 = {成员值}
#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;
}