cshapes.h
#ifndef cshapes.h
//#define cshapes.h#include <math.h>
#define M_PI 3.141592653523846#define T_circle 1
#define T_rectangle 2typedef struct circle_shape
{
short type;
double x,y;
double radius;
}circle_shape;typedef struct  rectangle_shape
{
short type;
double x1,y1;
double x2,y2;
}rectangle_shape;typedef union shape
{
short type;
circle_shape circle;
rectangle_shape rectangle;
}shape;double compute_area(shape *P_shape);void draw(shape *p_shape);#endifcshapes.cpp
#include <stdio.h>
#include "cshapes.h"double compute_area(shape *P_shape)
{
double area;
switch(p_shape->type)
{
case T_circle:
         area=M_PI*p_shape->circle.radius
*p_shape->circle.radius;
 break; case T_rectangle:
area=fabs(
(p_shape->rectangle x2-p.shape->rectangle.x1)*
(p_shape->rectangle y2-p.shape->rectangle.y1));
break;
default:
printf("Unknow shape in 'compate_area'!\n");
}
    return area;
}void draw(shape *p_shape)
{
printf("draw:");
switch(p_shape->type)
{
case T_circle:
printf("circle of radius %f at(%f,%f)\n",
p_shape->circle.radius,
p_shape->circle.radius,
p_shape->circle.x,
p_shape->circle.y
);
break;
case T_rectangle:
printf("rectangle with corners"
" (%f,%f) at(%f,%f)\n",
p_shape->rectangle.x1,
p_shape->rectangle.y1,
p_shape->rectangle.x2,
p_shape->rectangle.y2
);
break;
default:
printf("Unknow shape in draw!\n"); }
}
stest.cpp
#include <stdio.h>
#include "cshapes.h"int main()
{
int i;
shape s[2]; s[0].type=T_rectangle;
s[0].rectangle.x1=80.0;
s[0].rectangle.y1=30.0;
s[0].rectangle.x2=120.0;
s[0].rectangle.y2=50.0; s[1].type=T_circle;
s[1].circle.x=200.0;
s[1].circle.y=100.0;
s[1].circle.radius=50.0;

for(i=0;i<2;i++)
// printf("Area of shape[%d]=%f\n"+compate_area(&s[i])); for(i=0;i<2;i++)
draw(&s[i]);
return 0;}
帮忙看看哪里错误

解决方案 »

  1.   

    具体修改如下
    第一处:
    #ifndef _cshapes_h
    #define _cshapes_h
    #include <math.h> 
    #define M_PI 3.141592653523846 第二处:
    请注意你参数P_shape 而不是你所谓的p_shapedouble compute_area(shape *P_shape) 

    double area; 
    switch(P_shape->type) 

    case T_circle: 
            area=M_PI*P_shape->circle.radius 
    *P_shape->circle.radius; 
    break; 

    case T_rectangle: 
    area=fabs( 
    ((P_shape->rectangle.x2)-(P_shape->rectangle.x1))* 
    ((P_shape->rectangle.y2)-(P_shape->rectangle.y1))); 
    break; 
    default: 
    printf("Unknow shape in 'compate_area'!\n"); 

        return area; 
    } 运行结果:
    draw:rectangle with corners (80.000000,30.000000) at(120.000000,50.000000)
    draw:circle of radius 50.000000 at(50.000000,200.000000)