LINUX.ORG.RU

oop в «чистом» си


0

0

Пример этот был для lcc - и там он работает. gcc же выдает ожидаемые ошибки.
Но хотя бы в теории не могу понять, как это получается у lcc. Пример подсократил, но главное осталось. Как получается, что обращение my.StrCpyc() проходит, такого же указателя нет?? И кто передает первым параметром указатель на this, если в вызове этого нет??

// ______stringObject.h
typedef struct tagString String;
String NewString(char * s = NULL);
// the virtual table for the string objects
typedef struct{
int (*StrCpyc)(String *this, char * s);
void (*StrFree)(String *this);
}StringVtbl;
struct tagString {
StringVtbl * lpVtbl; // the vtbl
char * user; // pointer to array of chars to hold the C string
int max; // max capacity (num chars)
int len; // current length of C string
};
// ______stringObject.c
#include <stdlib.h>
#include <string.h>
#include "stringObject.h"
static int StrCpyc(String *this, char *s);
static void StrFree(String *this);
StringVtbl lpVtbl = {StrCpyc, StrFree};
String NewString(char * s = NULL)
{
String this;
this.lpVtbl = &lpVtbl; // address of the virtual table
this.user = NULL; // array of chars to hold the string
this.len = 0; // current length of C string
this.max = 0; // max capacity
if(s){this.StrCpyc(s);}
return this; // copy the struct to the caller.
}
static void StrFree(String *this)
{
if(this->user) free(this->user);
this->len = this->max = 0;
this->user = NULL;
}
static int StrCpyc(String *this, char * s)
{
char * tmp;
int len = strlen(s);
if(this->max < len){
if(this->user)
free(this->user);
tmp = malloc(len + 1);
if(!tmp){
return FAIL;
}else{
this->user = tmp;
this->len = this->max = len;
strcpy(this->user, s);
return this->len;
}
}else{
this->len = len;
strcpy(this->user, s);
return this->len;
}
}
// _______test.c
#include <stdio.h>
#include "stringObject.h"
int main(void)
{
char s[] = "Hello";
String my = NewString("All the world");
my.StrFree();
return 0;
}

anonymous

Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.