2009-11-17 789 views
-3

我想通过使用现有数据(半径,宽度和高度)来计算圆和矩形的面积。但我有一些错误,我希望你能帮我修复它。getArea()函数需要帮助

#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; 
} 
+0

而你的编译为C++,C _and_ C#和那里的错误是? – 2009-11-17 07:26:32

+0

那么,有什么错误? – Huppie 2009-11-17 07:31:20

+0

你真的有什么问题?请粘贴错误输出,或给出更清晰的问题。 – Shamster 2009-11-17 19:56:35

回答

7

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

0

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

+0

他不需要编写明确的析构函数,任何类都不需要手动释放任何资源。他应该删除他的形状。 – 2009-11-17 20:05:50

2

您可能还想重新考虑您的返回类型。

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