是前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;
}