C ++类名指针数组

时间:2013-03-12 15:49:50

标签: c++ arrays pointers dynamic-memory-allocation

我希望能够保存一个类名数组,并简单地将索引传递给一个函数,该函数将创建某个类的实例。我有内存限制,所以我不想简单地创建一个对象数组。

这是我最具描述性的伪代码:

类:

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 个答案:

答案 0 :(得分:3)

听起来你想要某种工厂:

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;
}

答案 1 :(得分:2)

创建std::vector<Shape*>然后您可以在C ++ 11中执行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;

答案 2 :(得分: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;
}

答案 3 :(得分: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;
}