【想学会面向对象】基类的虚函数,基类的派生类,如何处理undefined reference to

上题目

用虚函数计算各种图形的面积 (10 分)

定义抽象基类Shape,由它派生出五个派生类:Circle(圆形)、Square(正方形)、Rectangle( 长方形)、Trapezoid (梯形)和Triangle (三角形),用虚函数分别计算各种图形的面积,输出它们的面积和。要求用基类指针数组,每一个数组元素指向一个派生类的对象。PI=3.14159f,单精度浮点数计算。

输入格式:

输入在一行中,给出9个大于0的数,用空格分隔,分别代表圆的半径,正方形的边长,矩形的宽和高,梯形的上底、下底和高,三角形的底和高。

输出格式:

输出所有图形的面积和,小数点后保留3位有效数字。

输入样例:

12.6 3.5 4.5 8.4 2.0 4.5 3.2 4.5 8.4

输出样例:

578.109

唠嗑

其实是简单的题。训练一下以增强对“类和对象”知识点的理解。

1.中间遇见报错

  “ 1 个无法解析的外部命令 ”

“ undefined reference to `typeinfo for shape'” { return PI * t1 * t1; }{return 0.0;}

  为什么呢?因为我在写基类的时候是这么写的

class shape
{
public: 
    virtual float mian(void);
};

而按理是这样

class shape
{
public: 
    virtual float mian(void){return 0.0;}
};

上代码

#include <iostream>
using namespace std;
const float PI = 3.14159f;
class shape
{
public: 
    virtual float mian(void){return 0.0;}
};
class yuan :public shape 
{
public:float t1; float t2; float h; 
      yuan() {
                 t1 = 0; t2 = 0; h = 0;
             }
      float mian(void) { return PI * t1 * t1; }
};
class zheng :public shape
{
public: float t1; float t2; float h; 
      zheng() 
      {
    t1 = 0; t2 = 0; h = 0;
       } 
      float mian(void) { return t1 * t1; }
};
class chang :public shape
{
public:float t1; float t2; float h;
      chang()
      {
          t1 = 0; t2 = 0; h = 0;
      } 
      float mian(void) { return t1 * t2; }
};
class ti :public shape
{
public:float t1; float t2; float h;
      ti()
      {
          t1 = 0; t2 = 0; h = 0;
      } 
      float mian(void) { return (t1 + t2) * h / 2; }
};
class san :public shape
{
public: float t1; float t2; float h;
      san()
      {
          t1 = 0; t2 = 0; h = 0;
      }
      float mian(void) { return t1 * t2 / 2; }
};
int main()
{
    int i; float s=0;
    class shape *x[5];
    class yuan a; class zheng b; class chang c; class ti d; class san e;
    x[0] = &a; x[1] = &b; x[2] = &c; x[3] = &d; x[4] = &e;
    cin >> a.t1 >> b.t1 >> c.t1 >>c.t2 >> d.t1 >> d.t2 >> d.h >> e.t1 >> e.t2;
    for (i = 0; i < 5; i++)
    {
        s += x[i]->mian();
    }
    printf("%.3f", s);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值