看如下报错的原因是什么?谢谢
代码如下:
头文件:vector.h
- C/C++ code
#ifndef VECTOR_H#define VECTOR_Htemplate <typename object>class vector{ public: explicit vector(int ini_size = 0); vector(const vector &rhs); ~vector(); const vector & operator= (const vector &rhs); void size() const; void resize(int new_size); void reserve(int new_capacity); object & operator[](int index); const object & operator[](int index) const; void push_back(const object & x); enum{SPARE_CACPCITY = 16}; private: int the_size; int the_capacity; object *objects;};#endif
vector.cpp文件
- C/C++ code
#include "vector.h"vector::vector(int init_size):the_size(init_size),the_capacity(init_size + SPARE_CAPACITY){ the_size = init_size; objects = new object[the_capacity];}vector::vector(vector & rhs):objects(NULL){ operator=(rhs);}~vector::vector(){ delete [] objects;}const vector::vector & operator=(const vector & rhs){ if(this != &rhs){ delete [] objects; the_size = rhs.size(); the_capactity = rhs.the_capacity; objects = object[the_capacity]; for (int i = 0; i < the_size; i++){ objects[i] = rhs[i]; } return *this; }}void size() const{ return the_size;}void resize(int new_size){ if(new_size > the_capacity){ the_size = new_size * 2 + 1; reserve(the_size); } the_size = new_size;}void reserve(int new_capacity){ if(new_capacity < the_capacity){ return; } object * old_objects = objects; objects = new object[new_capacity]; for(int i=0; i < old_objects.size(); i++){ objects[i] = old_objects[i]; } the_capacity = new_capacity; delete [] old_objects;}object & operator[](int index){ return objects[index];}void push_back(object & x){ if(the_size == the_capacity){ reserve(2 * the_capacity + 1); } objects[the_size++] = x;}
main.cpp文件
- C/C++ code
#include "vector.h"#include <iostream>#include <string>using namespace std;int main(){ string str("abc"); vector<string> vc; vc.push_back(str); cout << vc[0] << endl; return 0;}
三个文件在同一个目录
使用下面的命令编译 g++ main.cpp -o main
报错信息如下:
/tmp/cc93OlsO.o: In function `main':
main.cpp:(.text+0x66): undefined reference to `vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::vector(int)'
main.cpp:(.text+0x79): undefined reference to `vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::push_back(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
main.cpp:(.text+0x8a): undefined reference to `vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::operator[](int)'
main.cpp:(.text+0xb5): undefined reference to `vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::~vector()'
main.cpp:(.text+0xc8): undefined reference to `vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::~vector()'
collect2: ld returned 1 exit status
请问
1、报错是什么意思
2.代码那里有问题导致报错?
------解决方案--------------------
模版类需要把实现也放到头文件里面. 而且你的实现也不对, 写成内联函数的方式吧.
[解决办法]
[解决办法]
另外,楼主,没事别搞些尽和标准库里东西重名的东西。