c 面向对象思想体现及多态方法(huabaojian ustc )

时间:2021-04-09 19:48:21

1.complex.h

 

#ifndef COMPLEX_H
#define COMPLEX_H

typedef struct complexStruct *complex;

complex newComplex (double x, double y);
complex complexAdd (complex c1, complex c2);
void complexOutput (complex c);
// other function prototypes are similar


#endif

2.intTuple.h

 

#ifndef TUPLE_H
#define TUPLE_H

typedef void *poly;
typedef void (*pt) (poly);

typedef struct tupleStruct *tuple;

tuple newTuple (poly n1, poly n2);
poly first (tuple t);
int tupleEquals (tuple t1, tuple t2);
void tupleOutput (tuple t);

#endif

3.complex.c

 

 

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

struct complexStruct
{
 void (*output)(complex);
 double x;
 double y;
};

complex newComplex (double x, double y)

 complex c;   
 
 c = (complex)malloc (sizeof (*c));
 c->output = complexOutput;
 c->x = x; 
 c->y = y; 
 return c;
}

complex complexAdd (complex c1, complex c2)
{
 complex c;  
 c = (complex)malloc (sizeof (*c));
 c->x = c1->x + c2->x; 
 c->y = c1->y + c2->y;
 return c;
}

void complexOutput (complex c)
{
 printf ("%lf+i%lf", c->x, c->y);
}

4.intTuple.c

 

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

struct a
{
 void (*output) (void *);
};


struct tupleStruct
{
 void (*output) (tuple);
 poly x;
 poly y;
};

tuple newTuple (poly n1, poly n2)
{
 tuple t;
 t = (tuple)malloc (sizeof (*t));
 t->output = tupleOutput;
 t->x = n1;
 t->y = n2;
 return t;
}

poly first (tuple t)
{
 // asldkjl;jf;
 return 0;
}

int tupleEquals (tuple t1, tuple t2)
{
 //return ((t1->x==t2->x) && (t1->y==t2->y));
 return t1==t2;
}

void tupleOutput (tuple t)
{
 void *p;
 struct a *q;
 
 printf ("(");
 p = t->x;
 q = (struct a *)p;
 q->output (t->x);
 printf (", ");
 p = t->y;
 q = (struct a *)p;
 q->output (t->y);
 printf (")/n");
}

 

main.c

 

#include "intTuple.h"
#include "complex.h"

void intOutput (int *p)
{
 printf ("%d", *p);
}

int main ()
{
 complex c1, c2;
 tuple t, t1;
 int *p;
 
 c1 = newComplex (3.14, 2.71);
 c2 = newComplex (9.0, 8.4); 
 t = newTuple (c1, c2);
 
 tupleOutput (t);
// p = (int *)malloc (sizeof (*p));
// *p = 88;
 t1 = newTuple (t, t); 
 tupleOutput (t1);
 //printf ("%d/n", tupleEquals (t, t1));
 
 return 0;
}