开发者

Need help on getArea() function

开发者 https://www.devze.com 2022-12-11 09:55 出处:网络
I\'m trying to calculate the area of the circle and the rectangle by using the existing data (radius ,width, and height). But i have some errors, i hope you can help me fix it.

I'm trying to calculate the area of the circle and the rectangle by using the existing data (radius ,width, and height). But i have some errors, i hope you can help me fix it.

#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 << "," << 开发者_如何学Pythony
     << "), 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;
}


Rectangle::GetArea method should be const. You declared it non-const, so it is not considered an override of Shape::GetArea, so Rectangle is considered abstract.


You may want to rethink your return type too.

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


As pointed by @Cătălin Pitiș, the GetArea() methods in derived classes need to be const. Otherwise compiler will complain that you have not provided the implementation for pure virtual functions (hence the derived classes become abstract) and will not allow you to create objects of the. Additionally, you need to declare a virtual destructor for Shape class. Otherwise, you will not be able release the memory properly. Also, you are not releasing the memory in main() function. You should use delete to release the memory allocated for the objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消