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

How to implement a custom class similar to a std::vector

本文关键字:vector 自定义 std 类似于 何实现 实现      更新时间:2023-10-16

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

Container <unsigned int> c;

这就是我重载<>运算符的方式......

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

没有operator <> . <>表示Container是一个类模板。 您需要以下语法:

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

最好的起点是找到一本好的C++书,但您也可以尝试阅读例如关于模板的C++常见问题解答页面。

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

简而言之,您想要的是:

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