以 C 實作物件導向的多型

高等 C 語言

簡介

字串

指標與陣列

函數

結構

物件導向

記憶體

檔案

錯誤處理

巨集處理

C 與組合語言

資料結構

動態字串

動態陣列

鏈結串列

雜湊表

開發環境

Make

Cygwin

MinGW

DevC++

wxDevC++

編譯器

gcc 編譯器

TinyCC 編譯器

LCC 編譯器

應用主題

CGI 程式

GNU 程式

視窗程式

影像處理

練習題

訊息

相關網站

參考文獻

最新修改

簡體版

English

程式範例:以 C 實作物件導向的多型範例

#include <stdio.h>
 
#define ShapeText(TYPE) void (*new)(struct TYPE*);float (*area)(struct TYPE*)
 
typedef struct _Shape { // Shape 物件,沒有欄位
  ShapeText(_Shape);
} Shape;
 
float ShapeArea(Shape *obj) { return 0; }
 
void ShapeNew(Shape *obj) {
  obj->new = ShapeNew;
  obj->area = ShapeArea;
}
 
typedef struct _Circle {
  ShapeText(_Circle);
  float r;
} Circle;
 
float CircleArea(Circle *obj) { return 3.14 * obj->r * obj->r; }
 
void CircleNew(Circle *obj) {
  obj->new = CircleNew;
  obj->area = CircleArea;
}
 
int main() {
  Shape s;
  ShapeNew(&s);  
  Circle c;
  CircleNew(&c);
  c.r = 3.0;
  Shape *list[] = { &s, (Shape*) &c };
  int i;
  for (i=0; i<2; i++) {
    Shape *o = list[i];
    printf("s.area()=%G\n", o->area(o));
  }
}

執行結果

D:\cp>gcc poly.c -o poly

D:\cp>poly
s.area()=0
s.area()=28.26

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License