我刚刚创建了这个新类:
//------------------------------------------------------------------------------
#ifndef MULTITHREADEDVECTOR_H
#define MULTITHREADEDVECTOR_H
//------------------------------------------------------------------------------
#include <vector>
#include <GL/GLFW.h>
//------------------------------------------------------------------------------
template<class T>
class MultithreadedVector {
public:
MultithreadedVector();
void push_back(T data);
void erase(typename std::vector<T>::iterator it);
std::vector<T> get_container();
private:
std::vector<T> container_;
GLFWmutex th_mutex_;
};
//------------------------------------------------------------------------------
#endif // MULTITHREADEDVECTOR_H_INCLUDED
//------------------------------------------------------------------------------
类的定义:
//------------------------------------------------------------------------------
#include "MultithreadedVector.h"
//------------------------------------------------------------------------------
using namespace std;
//------------------------------------------------------------------------------
template<class T>
MultithreadedVector<T>::MultithreadedVector() {
th_mutex_ = glfwCreateMutex();
}
template<class T>
void MultithreadedVector<T>::push_back(T data) {
glfwLockMutex(th_mutex_);
container_.push_back(data);
glfwUnlockMutex(th_mutex_);
}
template<class T>
void MultithreadedVector<T>::erase(typename vector<T>::iterator it) {
glfwLockMutex(th_mutex_);
container_.erase(it);
glfwUnlockMutex(th_mutex_);
}
template<class T>
vector<T> MultithreadedVector<T>::get_container() {
return container_;
}
现在的问题是,当我尝试在我的代码中将它用作另一个类的静态成员时:
// VehicleManager.h
#ifndef MULTITHREADEDVECTOR_H
#define MULTITHREADEDVECTOR_H
#include "MultithreadedVector.h"
#include "Vehicle.h"
class Foo {
public:
// stuffs
private:
static MultithreadedVector<Vehicle> vehicles_;
...
}
#endif
然后在里面:VehicleManager.cpp
#include "VehicleManager.h"
MultithreadedVector<Vehicle> VehicleManager::vehicles_;
void VehicleManager::Method() {
Vehicle vehicle;
VehicleManager::vehicles_.push_back(vehicle);
}
但它没有编译:(,我每次都会收到这个错误消息:
C:\***\VehicleManager.cpp|188|undefined reference to `MultithreadedVector<Vehicle>::push_back(Vehicle)'|
我真的不明白为什么,尤其是我在 VehicleManager.cpp 的全局范围内定义了静态类成员。
PS:我正在使用 Code::Blocks。
谢谢 !