【问题标题】:data type inst converting correctly?数据类型 inst 是否正确转换?
【发布时间】:2013-11-22 18:18:55
【问题描述】:

好的,所以我的 .exe 给了我一个零,所以我猜测数据类型没有正确转换。抱歉,我是 c++ 新手,来自 c。每当我在 c 中遇到这个问题时,通常都会被截断,但我无法找出我做错了什么。

//shape.h
#ifndef SHAPE_H
#define SHAPE_H
class shape 
{
public:
   shape();
   virtual float area()=0;

};

#endif SHAPE_H


//shape.cpp
#include <iostream>
#include "shape.h"
using namespace std;

shape::shape()
{
}

//triangle.h
#include"shape.h"

class triangle: public shape 
{
public: 
    triangle(float,float);
    virtual float area();
protected:
    float _height;
    float _base;


 };


//triangle.cpp
#include "triangle.h"

triangle::triangle(float base, float height)
{
base=_base;
height=_height;
}
 float triangle::area()
 {
return _base*_height*(1/2);
  }

//main.cpp
#include <iostream>
#include "shape.h"
#include "triangle.h"
using namespace std;

int main()
{

triangle  tri(4,2);


cout<<tri.area()<<endl;


return 0;
}

由于某种原因,我在我的 exe 中得到了一个零,而我应该得到一个 4。

【问题讨论】:

  • 这:(1/2) 的计算结果为零。它的整数除法。试试 1.0/2.0。

标签: c++ class inheritance polymorphism virtual-functions


【解决方案1】:

你以错误的方式赋值:

更新:

triangle::triangle(float base, float height)
{
  base=_base;
  height=_height;
}

到:

triangle::triangle(float base, float height)
{
   _base = base;
   _height = height;
}

编辑:

正如@WhozCraig 提到的,应该使用浮点数作为 1/2,或者只是

_base * _height / 2.0

【讨论】:

  • +1。我怀疑他也将找到我在评论中提到的内容(那些确实应该在初始化列表中=P)。
  • 谢谢!哈哈,你说得对,我确实找到了,但直到我按照 billz 所说的去做之前,它仍然没有任何作用
  • @FelixDaCat both 需要修复。任何一个都会做你所拥有的;两者都只是矫枉过正。 =P
  • 感谢 billz 的工作,但为什么分配它们的方式很重要?你能解释一下吗?因为我还在学习。谢谢! @billz
  • 您原来的base=_base; 是未定义的行为。您应该从参数中分配成员值,而不是相反
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多