C的函数指针实现C++的多态
C的函数指针很强大,用好了才是C语言的高手。像Gtk中的回调函数的使用,都体现了函数指针的强大威力。
struct Point{
int x, y;
};
/*Shape*/
/*----------------------------------------------------------------*/
struct Shape {
struct Methods* methods;
};
struct Methods {//将C++对应类中所有成员函数封装到一个结构体里面
float (*getCircle)(Shape * shape);
float (*getArea)(Shape * shape);
void (*draw)(Shape * shape);
void (*move)(Shape * shape);
};
////////////////C++ Counterpart of above code//////////////////
class Shape {
public:
virtual float getCircle() = 0;
virtual float getArea() = 0;
virtual void draw() = 0;
virtual void move() = 0;
};
///////////////////////////////////////////////////////////////
/*----------------------------------------------------------------*/
/*----------------------------------------------------------------*/
/*----------------------------------------------------------------*/
/*----------------------------------------------------------------*/
/*Rectangle*/
struct Rectangle {
struct Methods * methods; //包含封装后的成员函数结构体的指针
Point leftTop; //Shape之外派生的成员变量
Point rightBottom; //Shape之外派生的成员变量
};
float Rectangle_getCircle(Shape * shape)
{
Rectangle * r = (Rectangle *) shape;
return (r->rightBottom.x - r->leftTop.x +
r->rightBottom.y - r->leftTop.y) * 2;
}
float Rectangle_getArea(Shape * shape){}
void Rectangle_draw (Shape * shape){}
void Rectangle_move(Shape * shape){}
struct Methods rectangleMethods = {
&Rectangle_getCircle,
&Rectangle_getArea,
&Rectangle_draw,
&Rectangle_move,
};
////////////////C++ Counterpart of above code//////////////////
class Rectangle : public Shape {
Point leftTop;
Point rightBottom;
public:
virtual float getCircle();
virtual float
相关文档:
网络搜集-资料
格式化输入输出函数
Turbo C2.0 标准库提供的两个控制台格式化输入、 输出函数:printf( ) 、scanf()。
printf()函数用来向标准输出设备(屏幕)写数据;
scanf() 函数用来从标准输入设备(键 ......
在大型C语言项目工程或者linux内核中我们都会经常见到两个FASTCALL和armlinkage
两个标识符(修饰符),那么它们各有什么不同呢?今天就给大家共同分享一下自己的心得.
大家都知道在标准C系中函数的形参在实际传入参数的时候会涉及到参数存放的问题,那么这些参数存放在哪里呢? 有一定理论基础的 ......
1、bool、float、指针变量与"零值"比较的if语句?
答:
bool flag; if(flag),if(!flag)
char *p; if(p==NULL),if(p!=NULL)
float x;
const float EPSILON = 1e-6;
if((x>=-EPSILON)&&(x<=EPSILON)) //(-0.000001~0.000001)
if((x<-EPSILON)&& ......
这是入门篇中提到的那两题:
int * (* (*fp1) (int) ) [10];
int *( *( *arr[5])())();
解答如下
1.int * (* (*fp1) (int) ) [10];
从外往内进行分析
a.typedef P=(* (*fp1) (int) ),那么原声明改写为 int*P[10],这是一个有10个元素的数组,每个元素都是一个指向整型数的指针
b.typedef Q=(*fp1),那么P改写为 *Q( ......