问题描述
我正尝试在C中创建一个堆栈,这很有趣,并且想到了使用struct表示堆栈的想法.然后,将函数指针添加到针对push()和pop()操作的结构.
I'm trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop() operations.
到目前为止,看起来一切都很好,但是,对于push()和pop()函数的实现,我需要以某种方式引用*.那怎么办(可以吗?)?
So far all is good it seems, but, for the implementation of the push() and pop() functions I need to refer to *this somehow. How can that (can it?) be done?
这是我的结构
struct Stack {
int *data;
int current_size;
int max_size;
int (*push)(int);
int (*pop)();
};
以示例为例,
int push(int val) {
if(current_size == max_size -1)
return 0;
data[current_size] = val;
current_size++;
return 1;
}
您可以想象,编译器不知道current_size
是什么,因为它会像stack->current_size
这样.
As you can imagine, the compiler has no idea what current_size
is, as it would expect something like stack->current_size
.
这有可能克服吗?
推荐答案
C中没有隐式的this
.使其明确:
There's no implicit this
in C. Make it explicit:
int push(Stack* self, int val) {
if(self->current_size == self->max_size - 1)
return 0;
self->data[self->current_size] = val;
(self->current_size)++;
return 1;
}
您当然必须在每次调用push
和类似方法的过程中都将指向该结构的指针传递给我们.
You will of course have to pass the pointer to the struct into every call to push
and similar methods.
当您将Stack
定义为类而将push
等定义为方法时,这基本上就是C ++编译器为您所做的事情.
This is essentially what the C++ compiler is doing for you when you define Stack
as a class and push
et al as methods.
这篇关于“此" C语言中的指针(不是C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!