需要有关getArea()函数的帮助

时间:2009-11-17 07:22:49

标签: c++

我正在尝试使用现有数据(半径,宽度和高度)计算圆和矩形的面积。但是我有一些错误,希望你能帮我解决。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Shape
{
public:
    virtual void Draw () = 0;
    virtual void MoveTo (int newx, int newy) = 0;
    virtual int GetArea()const = 0;
};

class Rectangle : public Shape
{
public:
    Rectangle (int x, int y, int w, int h);
    virtual void Draw ();
    virtual void MoveTo (int newx, int newy);
    int GetArea() {return height * width;}

private:
    int x, y;
    int width;
    int height;
};

void Rectangle::Draw ()
{
    cout << "Drawing a Rectangle at (" << x << "," << y
     << "), width " << width << ", height " << height << "\n";
};

void Rectangle::MoveTo (int newx, int newy)
{
    x = newx;
    y = newy;
}
Rectangle::Rectangle (int initx, int inity, int initw, int inith)
{
    x = initx;
    y = inity;
    width = initw;
    height = inith;
}

class Circle : public Shape
{
public:
    Circle (int initx, int inity, int initr);
    virtual void Draw ();
    virtual void MoveTo (int newx, int newy);
    int GetArea() {return 3.14 * radius * radius;}

private:
    int x, y;
    int radius;
};

void Circle::Draw ()
{
    cout << "Drawing a Circle at (" << x << "," << y
     << "), radius " << radius <<"\n";
}

void Circle::MoveTo (int newx, int newy)
{
    x = newx;
    y = newy;
}

Circle::Circle (int initx, int inity, int initr)
{
    x = initx;
    y = inity;
    radius = initr;
}
int main ()
{
    Shape * shapes[2];
    shapes[0] = new Rectangle (10, 20, 5, 6);
    shapes[1] = new Circle (15, 25, 8);

    for (int i=0; i<2; ++i) {
    shapes[i]->Draw();
    shapes[i]->GetArea();
    }
    return 0;
}

3 个答案:

答案 0 :(得分:7)

Rectangle :: GetArea方法应该是const。你声明它是非const的,所以它不被认为是Shape :: GetArea的重写,所以Rectangle被认为是抽象的。

答案 1 :(得分:2)

您可能也想重新考虑您的退货类型。

int Circle::GetArea() {return 3.14 * radius * radius;}

答案 2 :(得分:0)

正如@CătălinPitiş所指出的,派生类中的GetArea()方法需要是const。否则编译器会抱怨您没有为纯虚函数提供实现(因此派生类变为抽象)并且不允许您创建对象。此外,您需要为Shape类声明一个虚拟析构函数。否则,您将无法正常释放内存。此外,您没有在main()函数中释放内存。您应该使用delete释放为对象分配的内存。