前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >函数和结构体

函数和结构体

作者头像
是小张啊喂
发布2022-08-18 17:30:55
3420
发布2022-08-18 17:30:55
举报
文章被收录于专栏:软件软件
函数声明和使用

.h文件用来声明函数 .cpp文件用来函数实现

例如:如何交换a和b的值 sawp.h

代码语言:javascript
复制
void swap(int a, int b);

sawp.cpp

代码语言:javascript
复制
#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

代码语言:javascript
复制
// 导入swap.h函数文件

#include "swap.h"
using namespace std;

int main() {
    int a = 10;
    int b = 20;
    // 调用明函数
    swap(a, b);
    return 0;
}
结构体的定义和使用

结构体: struct 结构体名 { 结构体成员列表 };

代码语言:javascript
复制
#include <iostream>

using namespace std;
struct Student {
    string name;
    int age;
    int score;
};

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

  • struct 结构体名 变量名
代码语言:javascript
复制
#include <iostream>
using namespace std;

int main() {
    // 可以省略 struct
    struct Student student;
    student.name = "小张";
    student.age = 21;
    cout << "姓名:" << student.name << ",年龄:" << student.age << endl;
}
  • struct 结构体名 变量名 = {成员值}
代码语言:javascript
复制
#include <iostream>
using namespace std;

int main() {
    // 可以省略 struct
    struct Student student{"小张", 21};
    cout << "姓名:" << student.name << ",年龄:" << student.age << endl;
}
  • 定义结构体是顺便创建变量
代码语言:javascript
复制
#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;
}

指针结构体

代码语言:javascript
复制
#include <iostream>
using namespace std;

int main() {
    Student student;
    struct Student *p = &student;
    p->name = "小张";
    p->age = 21;
    cout << "姓名:" << p->name << ",年龄:" << p->age << endl;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-05-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 函数声明和使用
  • 结构体的定义和使用
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档