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函数返回 a 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

创建一个std::vector<Shape*> 然后你可以v.emplace_back(new Triangle());在 C++11 中做。在 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 回答