注册 登录
编程论坛 C++教室

在继承与派生中的类型问题

whl20888 发布于 2008-12-13 22:17, 1093 次点击
#include <iostream.h>
#include <math.h>
double pi=3.14;
class shape
{
 public:
      float x,y,z;
      double s;
      shape(float x1,float  y1,float z1)
      {
          x=x1;
          y=y1;
          z=z1;
      }
};
class  circle: public shape
{
public:
    circle(float x2,float y2,float z2):shape(x2,y2,z2)
    {}
    double getarea()
    {
        s=pi*z*z;
        return s;
    }
};
class rectangle : public shape
{
public:
    float p;
    rectangle(float x2,float y2,float z2):shape(x2,y2,z2)
    {  p=(x+y+z)/2;}
    float getarea()
    {   
        s=sqrt(p*(p-x)*(p-y)*(p-z));
        return s;
    }
};
/*class  squre: public rectangle
{   public:
    int i;
    squre(float x3,float y3,float z3):rectangle(x3,y3,z3){i=9;}
   
};*/
void main()
{
    circle  c1(1.12,2.1,3.5);
    rectangle  t1(3,4,5);
    
    
    cout<<t1.getarea()<<endl<<c1.getarea()<<endl;
}
为什么这样可以运行,但当去掉注释符号,老是说类型不对,这是怎么回事呢,高手解释下了!

[[it] 本帖最后由 whl20888 于 2008-12-13 22:36 编辑 [/it]]
5 回复
#2
PcrazyC2008-12-13 23:43
你主函数里都没有用squre类,怎么会是这里的问题呢?主函数里怎么写的?
#3
sunkaidong2008-12-14 09:56
验证了下除了,有精度丢失以外没什么问题
#4
hitcolder2008-12-15 22:50
给加了几个强制类型转换,还用了个define,总算没warning了
#include <iostream.h>
#include <math.h>
#define pi (float)3.14
class shape
{
public:
      float x,y,z;
      float s;
      shape(float x1,float  y1,float z1)
      {
          x=x1;
          y=y1;
          z=z1;
      }
};
class  circle: public shape
{
public:
    circle(float x2,float y2,float z2):shape(x2,y2,z2)
    {}
    float getarea()
    {
        s=pi*z*z;
        return s;
    }
};
class rectangle : public shape
{
public:
    float p;
    rectangle(float x2,float y2,float z2):shape(x2,y2,z2)
    {  p=(x+y+z)/2;}
   float getarea()
    {   
        s=(float)sqrt(p*(p-x)*(p-y)*(p-z));
        return s;
    }
};

class  squre: public rectangle
{   public:
    int i;
    squre(float x3,float y3,float z3):rectangle(x3,y3,z3)
    {i=9;}
   
};

void main()
{
    circle  c1(1.12,2.1,3.5);
    rectangle  t1(3,4,5);
   
   
    cout<<t1.getarea()<<endl<<c1.getarea()<<endl;
}
#5
hitcolder2008-12-15 22:57
顺便说句: pi是被默认为const double类型的,你s设置成double类型的,而x,y,z却是float,计算的时候必然发生类型转换,肯定会有警告的,而且sqrt()函数的返回值好像是double型的吧。
1