1

クラス名の配列を保持し、特定のクラスのインスタンスを作成する関数に単にインデックスを渡すことができるようにしたいと考えています。メモリの制約があるため、単純にオブジェクトの配列を作成したくありません。

これが私の最もわかりやすい擬似コードです。

クラス:

class Shape
{
public:
    Shape();
};

class Square : public Shape
{
public:
    Square();
};

class Triangle : public Shape
{
public:
    Triangle();
};

主要:

int main()
{
    pointerToShapeClass arrayOfShapes[2];       // incorrect syntax - but
    arrayOfShapes[0] = pointerToSquareClass;    // how would i do this?
    arrayOfShapes[1] = pointerToTriangleClass;

    cin << myNumber;

    // Depending on input, create instance of class corresponding to array index
    if (myNumber == 0) { // create Square   instance }
    if (myNumber == 1) { // create Triangle instance }

    return 0;
}

これが紛らわしい場合は、説明を試みることができます。前もって感謝します!

編集:

本当に、クラスを実際にインスタンス化せずに、クラスへのポインタが必要なだけだと思います。

4

4 に答える 4

4

ある種の工場が必要なようです:

class Shape
{
public:
    Shape();
    static Shape* create(int id);
};

Shape* Shape::create(int id) {
  switch (id) {
    case 0: return new Square();
    case 1: return new Triangle();
  }
  return NULL;
}

次に、特定のShape特定のユーザー入力を作成する場合は、次のようにします。

int myNumber;
cin >> myNumber;
Shape* shape = Shape::create(myNumber);

これが最も単純な形です。ただし、関数が生のポインターではなく をcreate返すようにすることをお勧めします。std::unique_ptr<Shape>また、さまざまな ID を表す静的定数も設定します。

class Shape
{
public:
    Shape();
    static std::unique_ptr<Shape> create(int id);

    enum class Id { Square = 0, Triangle = 1 };
};

std::unique_ptr<Shape> Shape::create(Shape::Id id) {
  switch (id) {
    case Shape::Id::Square: return new Square();
    case Shape::Id::Triangle: return new Triangle();
  }
  return nullptr;
}
于 2013-03-12T16:01:21.660 に答える
2

a を作成すると、C++11 でstd::vector<Shape*> 実行できます。v.emplace_back(new Triangle());C++03 では使用できますv.push_back(new Triangle());

生の配列を使用できます

Shape* shapes[10]; // array of pointers;

shapes[0] = new Triangle(); 

テンプレートを使用してテンプレートを作成することもできます

template<typename ShapeType>
class Shape
{
 public:
     ShapeType draw(); 
     //All common Shape Operations
};

class Triangle
{
};

//C++11
using Triangle = Shape<Triangle>;
Triangle mytriangle;

//C++03
typedef Shape<Square> Square;
Square mysquare;
于 2013-03-12T15:53:10.403 に答える
2

これを試して:

int main()
{
    std::vector<Shape*> shapes;

    cin << myNumber;

    // Depending on input, create instance of class corresponding to array index
    if (myNumber == 0) { shapes.push_back(new Square(); }
    if (myNumber == 1) { shapes.push_back(new Triangle(); }

    return 0;
}
于 2013-03-12T15:53:45.893 に答える
1

私はこの関数を作成します:

Shape getNewShape(int shapeId)
{
    switch (shapeId)
    {
        case 1: return new Square();
        case 2: return new Triangle();
    }
    //here you should handle wrong shape id
}

次に、次のように使用します。

int main()
{
    cin << myNumber;

    // Depending on input, create instance of class corresponding to array index
    shape tempShape = getNewShape(myNumber);

    return 0;
}
于 2013-03-12T16:05:05.640 に答える