我像这样编译代码:c ++。\ Run.cpp。\ Vector.cpp Vector.cpp和Vector.h在同一文件夹中。 我已经看到许多有关此问题的主题,但是它们并没有帮助,我确定这是一个微型问题,但我看不到它。谢谢您的帮助!
这是Vector.h
#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
template <class T>
class Vector
{
private:
T *data;
size_t size;
public:
Vector() : data(nullptr), size(0) {}
Vector(const Vector<T> &v);
~Vector();
Vector<T> &operator=(const Vector<T> &v);
void push_back(T el);
void push_front(T el);
void erase(size_t i);
void clear();
bool contains(T el);
T &operator[](size_t i);
size_t length();
};
template <class T>
std::ostream &operator<<(std::ostream &os, const Vector<T> &v);
#endif
这是Vector.cpp
#include "Vector.h"
#include <iostream>
template<class T>
size_t Vector<T>::length(){
return size;
}
template<class T>
T &Vector<T>::operator[] (size_t i){
return data[i];
}
template<class T>
Vector<T>::Vector(const Vector& v) {
data = new T[v.size()];
for (size_t i = 0; i < v.size; i++)
{
data[i] = v[i];
}
size = v.size();
}
template<class T>
Vector<T> &Vector<T>::operator= (const Vector& v){
if(this != &v){
delete data;
data = new T[v.size];
for (size_t i = 0; i < v.size; i++)
{
data[i] = v[i];
}
size = v.size();
}
return *this;
}
template<class T>
Vector<T>::~Vector(){
delete data;
}
template<class T>
void Vector<T>::push_back(T el){
T* newData = new T[size+1];
for (size_t i = 0; i < size; i++)
{
newData[i] = data[i];
}
newData[size] = el;
size++;
delete data;
data = newData;
}
template<class T>
void Vector<T>::push_front(T el){
T* newData = new T[size+1];
for (size_t i = 0; i < size; i++)
{
newData[i+1] = data[i];
}
newData[0] = el;
size++;
delete data;
data = newData;
}
template<class T>
void Vector<T>::erase(size_t _i){
T* newData = new T[size-1];
for (size_t i = 0, j = 0; i < size; i++, j++)
{
if(i == _i){
i--;
continue;
}
newData[i] == data[j];
}
--size;
delete data;
data = newData;
}
run.cpp
#include "Vector.h"
#include <iostream>
using namespace std;
int main(){
Vector<int> v;
v.push_back(4);
cout << v << endl;
return 0;
}
错误:
未定义对Vector<int>::push_back(int)
的引用,
未定义对std::ostream& operator<< <int>(std::ostream&, Vector<int> const&)
的引用,未定义对Vector<int>::~Vector()
的引用,未对`Vector ::〜Vector()'的引用