【问题标题】:Template class T模板类 T
【发布时间】:2014-03-25 22:16:48
【问题描述】:

如果我有

template<class T> class Vector

public:
   Vector(const Vector& bla);

如何在 .h 文件之外使用它?

我试过 Vector&lt;T&gt;::Vector 但这不起作用。

.h 文件的某些部分

           Vector();

    Vector(int size, T value = T());

    Vector(const Vector& vec);

    ~Vector();

    T at(int index) const;

    void set_value_at(int index, T elem) const;

); //这是在同一个.h文件中但在类之外的代码

   Vector();

    Vector(int size, T value = T())
            {}

    Vector(const Vector& vec){}

    ~Vector(){}

    T at(int index) const{}

    void set_value_at(int index, T elem) const{}

【问题讨论】:

  • 请说的更清楚些。显示整个 .h 文件,以及您尝试使用它的位置/方式。

标签: c++ template-classes


【解决方案1】:

如果您尝试实施 Vector(),您可以这样做:

template<class T> Vector<T>::Vector(const Vector<T>& bla)
{
    ...
}

如果您尝试使用 Vector(),您可以这样做:

Vector<SomeTypeHere> vec1;
Vector<SomeTypeHere> vec2(vec1);

【讨论】:

  • 如果我在这个函数上使用它:templateVector::Vector(int size, T value = T()) 我得到这个错误:error: default argument given for 'Vector::Vector(int, T)'的参数2
  • 默认参数值只能在声明中指定,不能在实现中指定,例如:template &lt;class T&gt; Vector { public: Vector(int size, T value = T()); };template &lt;class T&gt; Vector&lt;T&gt;::Vector(int size, T value) {...},除非是内联在一起(使用模板时最常见),例如:template &lt;class T&gt; Vector { public : Vector(int size, T value = T()) { ... } };
【解决方案2】:

如果你做的一切都正确,Vector&lt;type&gt; v(args) 应该会自动调用看起来像构造函数的东西。使用其他功能:

v.myFunc();

静态函数:

Vector<type>::mystaticfunc();

【讨论】:

    猜你喜欢
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    相关资源
    最近更新 更多