【发布时间】:2019-08-14 21:29:09
【问题描述】:
出于教育目的,我正在尝试在 ANSI-C 中重新创建封装原则。我基本上所做的是在 .c 文件中创建一些结构:
struct _private
{
unsigned char SizeInBytes;
unsigned char* matrix;
struct Stack* S;
unsigned char ByteX;
};
它代表了我希望不被看到的变量。然后在结构(类)内的 .h 文件中,我创建了一个不透明的指针:
struct Maze
{
void* _private;
};
我稍后在构造函数中分配如下:
void* Maze_ctor(void* self, va_list *ap)
{
struct Maze* this = self;
this->DimX = va_arg(*ap, unsigned char);
this->DimY = va_arg(*ap, unsigned char);
this->_private = &(struct _private) // passing address of struct to void*
{
.SizeInBytes = this->DimX*this->DimY >> 1,
.S = new(Stack),
.ByteX = this->DimX % 8 > 0 ? this->DimX / 8 + 1 : this->DimX / 8
};
//
private.matrix = (unsigned char*)malloc(private.ByteX*this->DimY);
S = new(Stack); // this in my new() and it works similar to C++ new
for (int i = 0; i < private.ByteX*this->DimY; i++)
*(private.matrix + i) = 0;
}
此时一切正常,但我正在尝试调用 Next() 方法:
int Next(void* self, ...)
{
struct Maze* this = self;
struct _private *r = this->_private;
short t;
toBinary(this); // after this point the struct private breaks
}
toBinary()的原型是:
void toBinary(const void* self)
{
// somehow char local is defined and equals to 204??
struct Maze *this = self;
struct _private *r = this->_private;
unsigned char local; // right after this point SizeInBytes equals to 204!
...
}
问题是:如何解决这个问题。 禁止使用 C++! 对于感兴趣的人:这里是 new()
void* new(const void* _class,...)
{
const struct Class* class = _class; // we need to convert pointer from void* to class* safely
void *p = calloc(1, class->size); // allocation of memory for class .using size param
assert(p); // if Null -> throw an error
*(const struct Class**)p = class; // safe assignment of class pointer to (value) of p, to have memory and built in funcs
if (class->ctor) // if has constructor with some dynal in it, execute with varargs on its input
{
va_list ap;
va_start(ap, _class); //
p = class->ctor(p, &ap); // pass arguments as a list of pointers.
va_end(ap);
}
return p; //returns a pointer to class pointer (weird but worx)
}
【问题讨论】:
-
如果我没有完全弄错,您正在创建一个本地结构并将其分配给指针。函数完成后它就消失了,你有一个悬空指针。您需要动态内存分配。
-
@PaulOgilvie 编译器设置为 /TC,这应该是 C
-
您想要 C 还是 TC(无论 TC 是什么)?
-
@IlyaPakhmutov 如果您想在 C 中实现 OOP 的概念,您可以在网上找到很多课程。请在此处粘贴一段代码,我们可以执行该代码以了解您的意思。
-
@PaulOgilvie /TC 是用于编译 C 代码的 MSVC 编译器选项
标签: c class private encapsulation