2009-11-17 134 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;}