【问题标题】:How to write a copy constructor for Template Class - C++如何为模板类编写复制构造函数 - C++
【发布时间】:2013-02-12 01:29:50
【问题描述】:

在我的头文件中

template <typename T>
class Vector {
    public:
         // constructor and other things

         const Vector& operator=(const Vector &rhs);   
};

这是我迄今为止尝试过的一个声明

template <typename T> Vector& Vector< T >::operator=( const Vector &rhs )
{
    if( this != &rhs )
    {
        delete [ ] array;
        theSize = rhs.size();
        theCapacity = rhs.capacity();

        array = new T[ capacity() ];
        for( int i = 0; i < size(); i++ ){
            array[ i ] = rhs.array[ i ];
        }
    }
    return *this;
}

这是编译器告诉我的

In file included from Vector.h:96,
                 from main.cpp:2:
Vector.cpp:18: error: expected constructor, destructor, or type conversion before ‘&’ token
make: *** [project1] Error 1

如何正确声明复制构造函数?

注意:这是针对项目的,我无法更改标头声明,因此this 之类的建议虽然有用,但在此特定情况下没有帮助。

感谢您的帮助!

【问题讨论】:

    标签: c++ templates copy-constructor


    【解决方案1】:

    注意:您声明的是赋值运算符,而不是复制构造函数

    1. 您在返回类型之前错过了 const 限定符
    2. 您错过了返回类型和函数参数的模板参数 (&lt;T&gt;)

    使用这个:

    template <typename T>
    const Vector<T>& Vector<T>::operator=(const Vector<T>& rhs)
    

    【讨论】:

    • 函数参数不需要&lt;T&gt;,因为它位于成员名称operator=之后,并且注入的类名称在范围内。同样,你也可以template &lt;typename T&gt; auto Vector&lt;T&gt;::operator=(const Vector&amp; rhs) -&gt; Vector&amp;
    猜你喜欢
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多