2017-08-11 32 views
1

的類矩形和三角形都從Shape派生。我想添加另一個類ComplexShape,它可以是任何其他形狀的特定形狀。可通過類是通過實例來確定一個派生類的成員函數的行爲?

我知道有簡便的解決方法對於這個問題,像聲明一個變量來保存基類形狀的屬性,但我更感興趣的方式來ADRESS標題問題。如果可能,我如何定義ComplexShape的構造函數,以便ComplexShape使用用於初始化它的類的方法?

#include <iostream> 
#include <memory> 
#include <vector> 

class Shape { 
    public: virtual unsigned int getPointCount() const = 0; 
}; 

class Rectangle : public Shape { 
    public: unsigned int getPointCount() const { return 4; } 
}; 

class Triangle : public Shape { 
    public: unsigned int getPointCount() const { return 3; } 
}; 

class ComplexShape : public Shape { 
public: 
    std::vector<std::shared_ptr<Shape>> children; 

    //What Constructor comes here? 

    unsigned int getPointCount() const { 
     unsigned int i{ 0u }; 
     for(auto shape : children) i += shape->getPointCount(); 
     return i; 
    } 
}; 

int main() { 
    Triangle triangle(); 
    ComplexShape arrow; //How do I initialize this as a rectangle? 
    arrow.children.push_back(std::shared_ptr<Shape>(new Triangle())); 
    std::cout << arrow.getPointCount(); 
    return 0; 
}; 
+2

幽州複雜形狀形狀的集合,爲什麼不實現它這樣呢?我不認爲需要像你所要求的那樣「促進」其中一種形狀,就像「基礎」形狀一樣。 –

+1

要回答標題中的問題:我認爲不是。您可以將其作爲模板實現,然後您可以使用強類型成員來引用「主」形狀。 (我是一個C#開發,道歉,如果我的措辭是不正確。我指的是C#泛型) –

+0

搜索** Composite模式**,它會給你一個想法如何實現它。順便說一下,你的變量'children'應該是私人的。正如其他評論中指出的那樣,如果「主」形狀在子列表內部,情況可能會更好。 – Phil1970

回答

0

你可以在構造函數中使用初始化列表嘗試:http://www.cplusplus.com/reference/initializer_list/initializer_list/

#include <iostream> 
#include <memory> 
#include <vector> 
#include <initializer_list> 

class Shape { 
public: virtual unsigned int getPointCount() const = 0; 
}; 

class Rectangle : public Shape { 
public: unsigned int getPointCount() const { return 4; } 
}; 

class Triangle : public Shape { 
public: unsigned int getPointCount() const { return 3; } 
}; 

class ComplexShape : public Shape { 
public: 
    std::vector<std::shared_ptr<Shape>> children; 
    ComplexShape() {} 

    ComplexShape(std::initializer_list<std::shared_ptr<Shape>> init) : children(init) 
    { 
     // do some dynamic_cast magic here 
    } 

    unsigned int getPointCount() const { 
     unsigned int i{ 0u }; 
     for (auto shape : children) i += shape->getPointCount(); 
     return i; 
    } 
}; 

int main() { 
    Triangle triangle(); 
    ComplexShape arrow; //How do I initialize this as a rectangle? 
    arrow.children.push_back(std::shared_ptr<Shape>(new Triangle())); 
    std::cout << arrow.getPointCount(); 

    // This could be simplified probably 
    ComplexShape rect = { std::shared_ptr<Shape>(new Triangle()), std::shared_ptr<Shape>(new Triangle()) }; 
    return 0; 
}; 
相關問題