【发布时间】:2019-01-06 05:05:51
【问题描述】:
我正在尝试在普通成员函数中使用静态成员。但是编译器报告了一些错误。请看一下这段代码
#include <memory>
template<typename T>
class MyClass {
private:
static std::allocator<T> alloc;
T *p;
public:
void assign(T e) {
p = alloc.allocate(1);
alloc.construct(p, e);
}
};
这就是我使用它的方式:
#include 'myclass.h'
int main() {
MyClass<int> cls;
cls.assign(4);
};
编译器给出这个错误:
/Users/liuziqi/CLionProjects/cpplearning/src/tt.h:17:9: warning: instantiation of variable 'MyClass<int>::alloc' required here, but no definition is available [-Wundefined-var-template]
p = alloc.allocate(1);
^
/Users/liuziqi/CLionProjects/cpplearning/src/main.cpp:49:7: note: in instantiation of member function 'MyClass<int>::assign' requested here
cls.assign(4);
^
/Users/liuziqi/CLionProjects/cpplearning/src/tt.h:13:28: note: forward declaration of template entity is here
static std::allocator<T> alloc;
^
/Users/liuziqi/CLionProjects/cpplearning/src/tt.h:17:9: note: add an explicit instantiation declaration to suppress this warning if 'MyClass<int>::alloc' is explicitly instantiated in another translation unit
p = alloc.allocate(1);
我不知道哪一部分是错的.....我已经定义了静态成员和任何成员函数都应该能够使用它。此错误是否与 模板 相关? (我刚刚学习了模板,不确定我是否正确使用它。)
【问题讨论】:
标签: c++