2017-08-11 8 views
1

クラス四角形と三角形は、両方の形状に由来しています。別のクラスComplexShapeを追加したいと思います。複合シェイプは、他のシェイプを添付した特定のシェイプにすることができます。派生クラスのメンバ関数のふるまいを決定することができますか?

私はこの問題の簡単な回避策は、基本クラスでシェイプのプロパティを格納する変数を宣言するように、そこにある知っているが、私はタイトルの質問をアドレスする方法で、より興味があります。可能であれば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つを "促進"する必要性を見ません。私はノーだと思う:タイトルで質問に答える –

+1

。あなたは、あなたが「メイン」形状を参照するために、強く型付けされたメンバーを持って、それをテンプレートとして実装することができます。 (私はC#の開発者です。私の言葉が間違っているとお詫び申し上げます。私はC#ジェネリックスを参照しています) –

+0

検索**複合パターン**、それはあなたにそれを実装する方法を教えてくれます。ところで、あなたの変数「子供たち」はプライベートであるべきです。他のコメントに示されているように、 "メイン"シェイプが子リストの内側にある場合は、おそらく良いでしょう。 – 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; 
}; 
関連する問題