如何实现类似于std :: vector的自定义类

时间:2011-05-13 10:49:56

标签: c++ overloading

我的主题问题有点误导,我不想像std :: vector那样实现整个类,但是我希望能够创建一个名为Container的类,所以我可以像这样声明它:

Container <unsigned int> c;

这就是我如何重载&lt;&gt;操作者...

class Container
{
   private:
      Container() 
      {
         ...
      }

   public:
      void operator <>( unsigned int )
      {
         // what do I put here in the code?
         // maybe I call the private constructor...
         Container();
      }
};

2 个答案:

答案 0 :(得分:7)

没有operator <><>表示Container类模板。你需要的语法如下:

template <typename T>
class Container
{
    ...
};

最好的起点是找一本好的C ++书,但你也可以尝试阅读,例如C++ FAQ page about templates

答案 1 :(得分:1)

您应该了解有关模板的更多信息 http://www.cplusplus.com/doc/tutorial/templates/

简而言之,您想要的是:

template <class T>
class Container {
    ....
};