C++ 模板副本构造函数

C++ 模板副本构造函数,c++,C++,我需要为我的类MyVector创建一个副本构造函数 #include <iostream> using namespace std; template<class T> class MyVector{ private: T *v; int size; int max; public: MyVector(); MyVector(const MyVector &l);

我需要为我的类MyVector创建一个副本构造函数

#include <iostream> 
using namespace std;

template<class T>
class MyVector{
    private:
        T *v;
        int size;
        int max;

    public:
        MyVector();
        MyVector(const MyVector &l);
        MyVector& operator=(const MyVector &lhs);
        T &operator[](unsigned int i);
};

int main() {
    return 0;
}

template<class T>
MyVector& MyVector<T>::operator = (const MyVector &lhs){
    if (this == &lhs) return *this;

    for (int i = 0; i < size; ++i){
        delete v[i];
    }

    delete [] v;

    max = lhs.max;
    size = lhs.size;
    v = new T[max];

    for(int i = 0; i < size; ++i) {
        v[i] = new T(*(lhs.v[i]));
    }

    return *this;
}
#包括
使用名称空间std;
模板
类MyVector{
私人:
T*v;
整数大小;
int max;
公众:
MyVector();
MyVector(常数MyVector&l);
MyVector和运算符=(常量MyVector和lhs);
T&运算符[](无符号整数i);
};
int main(){
返回0;
}
模板
MyVector和MyVector::operator=(常量MyVector和lhs){
如果(this==&lhs)返回*this;
对于(int i=0;i
我得到了错误:
在–myVector–之前需要构造函数、析构函数或类型转换

不确定问题在哪里,我对C++是相当新的。 谢谢

应该是:

MyVector(const MyVector<T> &l);
MyVector(const MyVector&l);

同样,在其他任何地方,您都可以使用
MyVector
作为一个类型,因为没有模板参数,该类型是不完整的。

问题如下:

template<class T>
MyVector& MyVector<T>::operator = (const MyVector &lhs){
  /* ... */
}

在函数实现的返回中,写入
MyVector

模板
MyVector和MyVector::operator=(常量MyVector和lhs)
{
请注意,您实现的是赋值运算符,而不是复制构造函数

一个很好的替代方法是使用C++11语法,其中返回类型跟随函数头:

template<class T>
auto MyVector<T>::operator = (const MyVector &lhs)
    -> MyVector&
{
模板
自动MyVector::运算符=(常量MyVector和lhs)
->MyVector&
{

在模板类范围内,名称的使用隐含着完整的类型。因此在
MyVector
的范围内,名称
MyVector
的使用实际上是
MyVector
。谢谢!我完全忽略了这一点。谢谢!当我读到你的答案时,我意识到这就是问题所在。
template<class T>
MyVector<T>& MyVector<T>::operator = (const MyVector &lhs){
  /* ... */
}
template<class T>
MyVector<T>& MyVector<T>::operator = (const MyVector &lhs)
{
template<class T>
auto MyVector<T>::operator = (const MyVector &lhs)
    -> MyVector&
{