gpt4 book ai didi

C 私有(private)变量 Get 和 Set 方法

转载 作者:太空狗 更新时间:2023-10-29 16:57:57 26 4
gpt4 key购买 nike

我在 C 中工作,并且有一些我不想成为全局变量,但我确实希望为它们提供可以在文件外部“全局”访问的获取和设置方法。我习惯在 Java 中这样做,但 C 在这种方式上有很大不同。基本上,我正在寻找遵循此伪代码的内容,但我无法在任何地方找到我可能会查看的示例。

main.c
#include data.h
set(b);

datalog.c
#include data.h
get(b);

data.c
private int c;
set(b){
c = b;
}
get(c){
return c;
}

最佳答案

您将变量设置为static。当一个全局变量成为static时,它的范围被限制在当前文件中。

例子如下:

文件名:main.c

#include <stdio.h>

#include "header.h"

extern int get();
extern void set(int);

int main()
{
set(10);
printf("value = %d \n", get());
set(20);
printf("value = %d \n", get());
set(30);
printf("value = %d \n", get());
set(40);
printf("value = %d \n", get());
return 0;
}

文件名:header.h

#include <stdio.h>

int get(void);
void set(int);

文件名:header.c

#include "header.h"

static int value = 0;

int get(void)
{
return value;
}

void set(int new_value)
{
value = new_value;
}

输出:

$ gcc -Wall -o main main.c header.h header.c 
$ ./main
value = 10
value = 20
value = 30
value = 40
$

关于C 私有(private)变量 Get 和 Set 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10320025/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com