如果你想在c中使用私有变量,有许多技术可以接近一个私有变量,但是C语言实际上没有一个扩展到private,public,protected的“保护”概念(如C++一样)。
C的温度将显示任何变量(这是一个在C要求)的名所以你必须与信息隐藏类型的变量(决策提领相当困难的)想法接近它。
一个窍门是限定的变量作为void*
与实际变量的类型仅在一个.c
模块是已知的。
/* somefile.h */
extern void* counter;
/* somefile.c */
#include "somefile.h"
int actualCounter = 0;
void* counter = &actualCounter;
/* otherfile.c */
#include "somefile.h"
// we can see "counter", but we cannot "use" it here; because we don't have access
// to the real "hidden" type of "int".
更好的方法是使用struct
关键字来扩展这一理念,使伪方法,像这样
/* person.h */
struct s_person;
typedef Person struct s_person;
Person* new_Person(char* name);
void delete_Person(Person* person);
void Person_setName(Person* person, char* name);
char* Person_getName(Person* person);
/* person.c */
struct s_person {
char* name;
};
Person* new_Person(char* name) {
Person* object = (Person*)malloc(sizeof(struct s_person));
// duplicate the string for more security, otherwise constructor
// could manipulate the "private" string after construction.
object->name = strdup(name);
return object;
}
void delete_Person(Person* person) {
// some implementations pass a Person** to set the reference to 0
// this implementation requires that the caller sets his own references to 0
free(person->name);
free(person);
}
void Person_setName(Person* person, char* name) {
// free the old
free(person->name);
// duplicate the new to provide "out of simulated class" modification by malicious
// name setter.
person->name = strdup(name);
}
char* Person_getName(Person* person) {
// must return a copy, otherwise one can manipulate name
// from reference provided by Person_getName(...);
return strdup(person->name);
}
/* otherfile.c */
#include "Person.h"
/* Now we can hold Person "simulated objects", but we cannot */
/* manipulate their "state" without using the C simulated object */
/* methods */
int main(int argc, char** argv) {
Person* bob = new_Person("bob");
printf("%s\n", Person_getName(bob));
delete_Person(bob);
// critical or we hold a pointer to freed memory.
bob = 0;
return 0;
}
说这样的方法有几个变种,一个是有一个“公共结构“带有指向”私有结构“的void *指针。一种是将“方法”作为函数指针包含在“公共结构”(支持多态的一个步骤)中,一种是实际编写一个完整且正确的C++类型系统,试图按照C++的原则来解析事物(类层次结构,多态性,后期绑定,信息隐藏等)。基本上,你可以在没有太多工作的情况下获得一些“面向对象的内核”,但是当你添加更多的-ornamentation特性时,你将会添加更多的胶水代码(直到它是实际上更容易使用面向对象的编程语言)。
'C'没有'private'的概念。也许试着看'静态'全局变量。 – RageD 2012-04-25 16:40:40
因此我的问题。我如何欺骗C? – Reid 2012-04-25 16:41:18
这取决于你想要做什么。由于'C'不是OOP(它是面向函数的),你将不得不使用函数和'结构'或全局变量。 – RageD 2012-04-25 16:43:34