C:你如何模拟'实例'?

And*_*ech 1 c oop stack instance

假设我在C中有以下代码表示堆栈:

#define MAX 1000

int arr[MAX];
static int counter = 0;
isstackempty()
{
    return counter <= 0;
}
void push(int n)
{
    if (counter >= MAX) {
        printf("Stack is full.  Couldn't push %d", n);
        return;
    }
    arr[counter++] = n;
}

int pop(int* n)
{
    if(isstackempty() || n == 0) {
        printf("Stack is empty\n");
        return 0;
    }
    *n = arr[--counter];
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码在一个stack.c文件中,函数原型在一个头文件中.


现在,来自C#和OO背景,如果我想要stack在我的应用程序中分离s,在OO语言中我将创建两个实例.但是在C中,你如何处理这种情况?

假设我想stack在我的C代码中使用两个单独的s ...使用上面的代码,我将如何处理它?

Jes*_*erE 10

把数组arr放在一个struct.

struct stack {
    int arr[MAX];
    ...
}
Run Code Online (Sandbox Code Playgroud)

这个结构成为你的实例.然后,您可以在堆栈上声明它:

struct stack mystack;
Run Code Online (Sandbox Code Playgroud)

或者在堆上使用malloc:

struct stack *mystack = malloc(sizeof(struct stack));
Run Code Online (Sandbox Code Playgroud)

您还需要将指向实例的指针作为操作实例的任何函数的第一个参数传递.


Fal*_*ina 7

C方法是将你的'对象'的所有状态包装到一个结构中,然后显式地将它传递给所有在堆栈上运行的函数,所以它应该是:

typedef struct _stack {
  int arr[MAX];
  int counter;
} stack;

int isstackempty(stack *s)
{
    return s->counter <= 0;
}

int push(stack *s, int n)
{
    if (s->counter >= MAX) {
        printf("Stack is full.  Couldn't push %d", n);
        return -1;
    }
    arr[s->counter++] = n;
    return 0
}

int pop(stack *s, int *n)
{
    if(isstackempty(s) || n == 0) {
        printf("Stack is empty\n");
        return -1;
    }
    *n = arr[--s->counter];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

您的示例的问题是您正在编写函数定义,就像我们有一个基于类的对象结构,C没有.考虑如何在C中完成它的最简单方法是,您正在编写需要您明确传入'this'参数的方法.

你也可以拥有相当于构造函数和析构函数的东西,它们可以进一步抽象你的"对象".

stack* newStack() {
    stack* s = malloc(sizeof(stack));
    s->counter = 0;
    return s;
}

void freeStack(stack* s) {
    free(s);
}
Run Code Online (Sandbox Code Playgroud)