網站首頁 編程語言 正文
如何在結構體內定義函數
結構體中引入函數
#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
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2023-01-02 Flutter?包管理器和資源管理使用學習_Android
- 2022-07-21 IC設計中glitch free時鐘選擇器的設計過程
- 2022-10-20 詳解Python中的?type()函數_python
- 2022-08-22 詳解golang執行Linux?shell命令完整場景下的使用方法_Golang
- 2022-10-17 VSCode安裝Django插件后實現html語法提示的方法步驟_python
- 2023-07-27 修改el-button 的樣式
- 2022-07-07 Asp.Net上傳文件并配置可上傳大文件的方法_基礎應用
- 2022-02-04 sql語句:and與or的優先級
- 欄目分類
-
- 最近更新
-
- 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同步修改后的遠程分支