2015-05-08 37 views
-1

所以我得到了這個例子:給予矢量不同的數字找出多少圈,有多少平方

class figures 
    {}; 

    class square:public figures 
    {}; 

    class circle : public figures 
    {}; 


    ..... 

    int main() 
    { 
    geometric figures* *p; 

    p[0]=new Circle; 
    p[1]=new Square; 

return 0; 
    }; 

等。我的問題是,如果所有的指針都是幾何圖形類型,我怎麼才能找出我的幾何圖形數組中有多少個圓或正方形?

+1

這裏有多個問題......標識符名稱(幾何圖形)中不能有空格,並且,您從未分配過數組'p'。也許你正在尋找std :: vector來代替? – MuertoExcobito

+0

爲什麼不保持運行總計? –

回答

0

你可以使用動態轉換。例如:

// Returns true if 'a' is of type 'square' 
bool isSquare(Figure* a) 
{ 
    return dynamic_cast<Square*>(a) != nullptr; 
} 
// Returns true if 'a' is of type 'circle'  
bool isCircle(Figure* a) 
{ 
    return dynamic_cast<Circle*>(a) != nullptr; 
} 
int main() 
{ 
    Figure *p = new Figure[5]; 
    p[0] = new Circle; 
    p[1] = new Circle; 
    p[2] = new Square; 
    p[3] = new Square; 
    p[4] = new Square; 
    int circleCnt = 0; 
    int squareCnt = 0; 
    for(int i = 0; i < 5; i++) 
    { 
     if(isCircle(p[i])) 
     { 
      circleCnt++; 
     } 
     if(isSquare(p[i])) 
     { 
      squareCnt++; 
     } 
    } 
    cout << "Number of circles: " << circleCnt << endl; 
    cout << "Number of squares: " << squareCnt << endl; 
} 

該程序的輸出將是:
編號圓圈:2
方格數:3

注意這是非常低效相比保持圈的數量和方塊最新的地方。

+0

謝謝!我知道效率很低,但實際上這個任務是查看圖形矢量中有多少個圓形和正方形,而不計算它們,因爲我將它放在矢量中。是這樣的:給定一個具有不同數字的矢量,找出有多少個圓圈。 – Radu

1

您可以使用dynamic_cast

std::vector<geometric_figures *> shapes; 
int num_circles = 0; 
int num_squares = 0; 
for (geometric_figures * shape : shapes) 
{ 
    if(dynamic_cast<circle*>(shape)) 
     num_circles++; 
    if(dynamic_cast<square*>)(shape)) 
     num_squares++; 
} 

你也可以添加一個enum對應形狀的類型,並添加GetType()方法返回enum

1

你去你的班上有一個enum

class geometric_figures 
{ 
public: 
    enum shape {eSquare, eCircle}; 
    virtual shape GetShapeType() const = 0; 
}; 

class square : public geometric_figures 
{ 
public: 
    shape GetShapeType() const override { return eSquare; } 
}; 

class circle : public geometric_figures 
{ 
public: 
    shape GetShapeType() const override { return eCircle; } 
}; 

然後你可以使用std::count_if

#include <algorithm> 
#include <vector> 
int main() 
{ 
    using GF = geometric_figures; 
    std::vector<GF*> p; 

    p.push_back(new circle); 
    p.push_back(new square); 

    int num_circles = std::count_if(p.begin(), p.end(), [](GF const* fig){ return fig->GetShapeType() == GF::eCircle; }); 

} 

Working demo