【问题标题】:Array of Generic Class Objects C++泛型类对象数组 C++
【发布时间】:2017-09-19 03:50:57
【问题描述】:

我有一个通用类Queue,其中包含一个模板Ttype2,作为将存储在每个节点的信息字段中的数据类型的放置持有者。 在我的驱动程序类中,我想实例化一个 Queue 类对象数组,但我似乎无法弄清楚。我该怎么做呢?

这些没有用,但说明了我想要完成的工作:

// Queue Complex[] = new Queue();//invalid use of template name without identifier list
 //Queue<Ttype2> Complex[]; //template arg 1 is invalid
// vector<Queue> Complex2[];//invalid template arguments`

Queue.h 头中的队列类声明和构造函数:

template <typename Ttype2>
class Queue
{
  // Global Data Items
  protected:
  Node <Ttype2> Front, Rear;
  int Length;

  // member function prototypes
  public:
  Queue();
  void AddRear(Node <Ttype2> ThisNode);
  Node <Ttype2> RemoveFront();
  void Modify(int Position, Node <Ttype2> ThisNode);
  void ClearAll();
  int GetSize();`
  Node <Ttype2> GetNode(int Position);
  Node <Ttype2>* toArray();
};`

// Constructor
template <typename Ttype2>
Queue <Ttype2> :: Queue()
{
  Rear = Front = NULL;
  Length = 0;
} // End of Constructor
`

【问题讨论】:

  • 我需要实现一个泛型数组类来保存这些泛型对象吗?

标签: c++ arrays object generics queue


【解决方案1】:

这行得通:

Queue<int> *Complex = new Queue<int>();
Queue<int> Complex[1];
vector<Queue<int>> Complex2[1];

您需要在实例化模板时为模板提供真正的参数。

Queue<Ttype2> // Ttype2 isn't a real type, use int, char, ...

您还需要定义您的类型Node&lt;&gt;。如果你想将NULL 分配给RearFront 它,首先考虑使它们成为指针,然后使用nullptr 而不是NULL

【讨论】:

    【解决方案2】:

    如果我想在一个数组中保留许多不同的Queue&lt;XXX&gt;,我将添加到 Yola 的解决方案中,
    我一般创建一个接口类Queue_base

    class Queue_base{
        public: virtual void func()=0;
    };
    
    template <typename Ttype2>class Queue : public Queue_base{
        public: void func(){
            //... some code
        }
    };
    
    int main() {
        Queue_base* complex[2];
        complex[0]=new Queue<int>();
        complex[1]=new Queue<float>();
        complex[0]->func(); 
        std::vector<Queue_base*> complex2;
        complex2.push_back(new Queue<char>());
        Queue<int>* c1=static_cast<Queue<int>*>(complex[0]);
        return 0;
    }
    

    这里是直播demo
    请注意,使用虚函数会稍微降低性能。

    它也会丢失类型(减少到Queue_base*)并限制一些函数调用,但它对于一些实际情况很有用。

    为了扩展它的用法,Node&lt;T&gt; 也可以从一个新类Node_Base 继承,该类具有Node&lt;T&gt; 的所有通用功能,例如:-

    template <typename Ttype2> class Queue : public Queue_Base{
      // Global Data Items
      protected:
      Node_Base* Front; //Front = new Node<Ttype2>();
      Node_Base* Rear;     
    

    不过,这取决于您的需求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多