带模板的程序给我未定义的引用

时间:2014-06-03 15:55:46

标签: c++ templates

我是C ++编程的新手,所以我练习一个简单的类只是为了习惯语法。 这里有我的文件:

Vector.h

#ifndef VECTOR_H_
#define VECTOR_H_

namespace myCode {

template<typename T>
class Vector{
    private:
        T * elem;
        int sz;
    public:
        Vector(int s);
        Vector(const Vector& a);    //copy constructor
        Vector& operator=(const Vector& a); //copy assignment
        Vector(Vector&& a); //move constructor
        Vector& operator=(Vector&& a);  //move assignment
        ~Vector();  //destructor
        T& operator[](int i);
        int size() const;
};


}  // namespace myCode

#endif /* VECTOR_H_ */

Vector.cpp

#include "Vector.h"
#include <stdexcept>

template<typename T>
myCode::Vector<T>::Vector(int s){
    if(s<0)
        throw std::length_error();
    elem = new T[s];
    sz =s;
}
template<typename T>
myCode::Vector<T>::Vector(const Vector<T>& a):
elem{new T[a.sz]}, sz{a.sz}
{
    for(int i=0; i< sz; ++i){
        elem[i] = a.elem[i];
    }
}   //copy constructor

template<typename T>
myCode::Vector<T>& myCode::Vector<T>::operator=(const Vector<T>& a){
    T* p = new T[a.sz];
    for(int i=0; i< a.sz; ++i){
        p[i]= a.elem[i];
    }
    delete[] elem;
    elem = p;
    sz = a.sz;
    return *this;   \
}   //copy assignment

template<typename T>
myCode::Vector<T>::Vector(Vector&& a):elem{a.elem}, sz{a.sz}{
    a.elem = nullptr;
    a.sz = 0;
}   //move constructor

template<typename T>
myCode::Vector<T>& myCode::Vector<T>::operator=(Vector&& a){
    delete[] elem;
    elem = a.elem;
    sz = a.sz;
    a.elem=nullptr;
    a.sz=0;
    return *this;
}   //move assignment

template<typename T>
myCode::Vector<T>::~Vector(){
    delete[] elem;
}   //destructor

template<typename T>
T& myCode::Vector<T>::operator[](int i){
    if(i>sz || i < 0)
        throw std::out_of_range();
    return elem[i];
}

template<typename T>
int myCode::Vector<T>::size() const{
    return sz;
}

的main.cpp

#include "Vector.h"
#include <iostream>
#include <string>

int main(){
    myCode::Vector<std::string> v(10);
    std::cout << v.size();
    return 0;
}

但是,这个小程序给了我以下输出:

main.o: In function `main':
C:\Users\Papero\workspacePR\VectorClassComplete\Debug/../main.cpp:13: undefined reference to `myCode::Vector<std::string>::Vector(int)'
C:\Users\Papero\workspacePR\VectorClassComplete\Debug/../main.cpp:14: undefined reference to `myCode::Vector<std::string>::size() const'
C:\Users\Papero\workspacePR\VectorClassComplete\Debug/../main.cpp:15: undefined reference to `myCode::Vector<std::string>::~Vector()'
C:\Users\Papero\workspacePR\VectorClassComplete\Debug/../main.cpp:15: undefined reference to `myCode::Vector<std::string>::~Vector()'
编辑:我已经尝试编译eclipse和代码块,并启用了c ++ 11支持。

0 个答案:

没有答案