设为首页 加入收藏

TOP

C语言实现多态(二)
2015-01-21 11:08:27 来源: 作者: 【 】 浏览:41
Tags:语言 实现
是前4个字节,在Square的内存模型是第三个4字节的位置
?
square.print();?
上面的代码使用第三个字节的指针来调用print函数,下面的代码期望完成一样的功能
?
(*pointer).print();?
但是在最前4个字节没有指针,而是int类型的值,2个字节,但是我们的指针不会意识到是2个字节,于是找到内存的位置为2的位置(可能是一些B IOS驱动\操作 系统内存地址),从而导致中断错误的产生
?
既然我们知道了原因,那么可以找到一个解决方案(不是最好),只有当Shape结构中的print函数的指针在第三个4字节的位置,那么可以填充Shape的前8个字节,这种方法就是C语言中的“填充”技术,代码如下:
?
struct Shape{
? ? char padd[8];
? ? void (* print)( void );
? ? float (* area)( struct Shape * this ); ? ?
};?
修改后测试代码如下:
?
#include
//abstract father class
/*
struct Shape{
? ? void (* print)( void );
? ? float (* area)( struct Shape * this ); ? ?
};?
*/
struct Shape{
? ? char padd[8];
? ? void (* print)( void );
? ? float (* area)( struct Shape * this ); ? ?
};?
?
struct Square{
? ? float width;
? ? float height;
? ??
? ? //now for functions
? ? void (* print)( void );
? ? float (* area)( struct Square * this );
};?
?
void print_square( void ){
? ? printf("Hello Square\n");
}?
?
float calc_square_area(struct Square * this){
? ? return (*this).width * (*this).height;
}?
?
void init_square(struct Square * square, float w, float h ){
? ? (*square).width = w;
? ? (*square).height = h;
? ? (*square).print = print_square;
? ? (*square).area = calc_square_area;
}?
?
int main(void)
{
? ? struct Square square;?
? ? struct Shape *p = (struct Shape*)□
? ? init_square( &square, 2, 2 );
? ? //square.print();?
? ? (*p).print();
? ? printf("the area of the square is %.2f\n", square.area(&square));
? ? return 0;
}
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C指针编程之道 ---第六次笔记 下一篇C语言之霍夫曼编码学习

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: