2016-04-14 8 views
0

私はオブジェクト指向のCの基本を教えようとしています。私はvtablesをビルドしようとしていて、それらを使って構造体の "継承"をシミュレートしようとしています(C++のクラス継承をコピーしようとします)。オブジェクト指向C:ビルディングvtables

私は質問があります。私はそれが可能だと信じていますが、私はそれを行う方法がわかりません。 "derived"構造体の変数を "base"構造体のポインタから変更できますか?

#include <stdio.h> 
#include <stdlib.h> 

//should represent Base 
typedef struct Animal 
{ 
    int age; 
    void *vtable; 
} Animal; 

//Cat and dog will inherit Animal. They both have same 'age' variable, and different other parameters 
typedef struct Dog 
{ 
    int age; 
    double weight; 
    void *vtable; 
} Dog; 

typedef struct Cat 
{ 
    int age; 
    int numberOfLives; 
    void *vtable; 
} Cat; 

//some test functions 
void Speak_Dog(Animal* a) 
{ 
    printf("Woof!\n"); 
} 

void Speak_Cat(Animal* a) 
{ 
    printf("Meow!\n"); 
} 

//this is where I'm stuck, I would like to keep sending pointer to Animal 
double Dog_GetCost(Animal *a) 
{ 
    return 0;//should return age*weight 
} 

double Cat_GetCost(Animal *a) 
{ 
    return 0; //should return age*num_lives 
} 

//build tables 
void* Dog_Vtable[2] = {Speak_Dog, Dog_GetCost}; 
void* Cat_Vtable[2] = {Speak_Cat, Cat_GetCost}; 

void Construct_Dog(Dog* d) 
{ 
    d->age = 0; 
    d->weight = 0; 
    d->vtable = Dog_Vtable; 
} 

void Construct_Cat(Cat* c) 
{ 
    c->age = 0; 
    c->numberOfLives = 0; 
    c->vtable = Cat_Vtable; 
} 

int main() 
{ 
    int choice; 
    Dog d; 
    Cat c; 
    Animal* a; 

    ((void (*)(Animal*))Dog_Vtable[0])((Animal*)&d); //print out "woof" - good 
    ((void (*)(Animal*))Cat_Vtable[0])((Animal*)&c); //print out "meow" - good 

    printf("Do you want to make dog or a cat? (0/1) "); 
    scanf("%d", &choice); 

    if(choice == 0) 
    { 
     a = &d; //animal is Dog 
     a = (Animal*)malloc(sizeof(Dog)); //allocate memory for Dog 
     Construct_Dog(a); //construct it 
    } 
    else 
    { 
     a = &c; //similar for cat 
     a = (Animal*)malloc(sizeof(Cat)); 
     Construct_Cat(a); 
    } 

    free(a); 

    return 0; 
} 

さて、私は*aを使用して、それをどのように変化するか、のは、私は2番目のint型変数(重量またはNumLives、依存する)を変更してみましょうか? 私はObject oriented programming with ANSI-Cから学びたいと思っていますが、これを理解することはできません。

+1

を使用することができます - >重量= 33.3;しかし、この場合、あなたはoopの抽象を失います。 – fluter

+0

私はまだ 'switch'などを使用して、それが何であるかを判断できます。だから、これはかなり良いと思う。少しでもテストされます! – Rorschach

+0

コードが壊れています。 Cは、任意の型からの型変換を定義していません。 – 2501

答えて

0

事前にタイプ犬のISを知っていればあなただけ行う((犬*)a)に、((Dog *)a) -> weight = 42.0;または((Cat *)a) -> numberOfLives = 9;

関連する問題