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
相关文档:
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)&& ......
C++/C试题
本试题仅用于考查C++/C程序员的基本编程技能。内容限于C++/C常用语法,不涉及数据结构、算法以及深奥的语法。考试成绩能反映出考生的编程质量以及对C++/C的理解程度,但不能反映考生的智力和软件开发能力。
笔试时间90分钟。请考生认真答题,切勿 ......
系统环境:Ubuntu 9.04
软件环境:NetBeans 6.7.1 C/C++ 、JDK1.6.0_16
本次目的:完成NetBeans 6.7.1 C/C++ 的配置工作、编译测试及对中文支持
首先从官网上下载最新版的Netbeans 选择C/C++工作台下载[点击进入],弹出的新网页将会自动下载,如下图:
在进行安装之前,我们先安装JDK, ......
在使用C语言编写大型工程时要用到面向对象语言中的一些特性(内核中某些部分就应用了这些特性)。C语言是基于文件的类,static关键字声明私有数据成员,公有数据成员必须定义到头文件,或由其它文件使用extern关键字声明来使用。但后者引用关系不清晰。头文件就成了公有数据成员声明的地方。
头文件中应该包含以下及方面内 ......