網站首頁 編程語言 正文
如何在結構體內定義函數
結構體中引入函數
#include <stdio.h>
struct student {
?? ?char *name;
?? ?int age;
?? ?void (*printInfo)(struct student *stu);
};
void printInfo(struct student *stu)
{
?? ?printf("name = %s, age = %d", stu->name, stu->age);
}
int main(int argc, char**argv)
{
?? ?struct student students[] = {
?? ??? ?{"zhangsan", 10, printInfo},
?? ??? ?{"lisi", 26, printInfo},
?? ?};
?? ?students[0].printInfo(&students[0]);
?? ?students[1].printInfo(&students[1]);
}
C++中結構體引入
#include <stdio.h>
struct student {
?? ?char *name;
?? ?int age;
?? ?void printInfo(void)
?? ?{
?? ??? ?printf("name = %s, age = %d\n", name, age);
?? ?}
};
int main(int argc, char**argv)
{
?? ?struct student students[] = {
?? ??? ?{"zhangsan", 10},
?? ??? ?{"lisi", 26},
?? ?};
?? ?students[0].printInfo();
?? ?students[1].printInfo();
}
C++中類引入
#include <stdio.h>
class student {
public:
?? ?char *name;
?? ?int age;
?? ?void printInfo(void)
?? ?{
?? ??? ?printf("name = %s, age = %d\n", name, age);
?? ?}
};
int main(int argc, char**argv)
{
?? ?struct student students[] = {
?? ??? ?{"zhangsan", 10},
?? ??? ?{"lisi", 26},
?? ?};
?? ?students[0].printInfo();
?? ?students[1].printInfo();
}
結構體成員有函數的定義與使用
```c
#include <stdio.h>
typedef int (*FunHandle)(int, int); //定義 指向函數的指針
struct Example
{
int a;
int b;
FunHandle fun; //函數作為結構體成員
};
int add(int, int);
int main()
{
struct Example ex;
int r;
ex.a = 1;
ex.b = 2;
ex.fun = add;
r = ex.fun(ex.a, ex.b); //結構體中函數的 使用
printf("%d + %d = %d \n", ex.a, ex.b, r);
return 0;
}
int add(int a, int b)
{
return a+b;
總結
原文鏈接:https://blog.csdn.net/qq_43566054/article/details/104211794
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2022-10-01 Android11及以上文件讀寫權限申請詳細介紹_Android
- 2023-07-08 編寫socket配置文件
- 2022-06-21 C++簡明分析臨時對象是什么_C 語言
- 2023-01-26 Python+Sklearn實現異常檢測_python
- 2023-01-12 Kotlin注解實現Parcelable序列化流程詳解_Android
- 2021-12-15 go語言處理TCP拆包/粘包的具體實現_Golang
- 2022-09-17 ASP.NET?Core實現AES-GCM加密算法_實用技巧
- 2023-05-03 C++類與對象的基礎知識點詳細分析_C 語言
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支