[英]C++: unique_ptr not initializing correctly
myMain.cpp
:
#include <memory>
#include "myClass.h"
static std::unique_ptr<myClass> classPtr; // Error thrown here
...
我正在全局范围内进行初始化,因为将所有数据加载到此类的属性中需要一段时间,因此我想执行一次,并使该数据持久保存,直到我给出明确的命令删除它为止( classPtr.reset(nullptr)
)。
当我尝试编译时: g++ myMain.cpp -o myMain.o
我得到: error: expected initializer before '<' token
。
为什么会出现此错误?
我已经在myClass.h
和myClass.cpp
定义了myClass
; 我认为该错误与构造函数有关。 我简化了代码并仅包含下面的重要内容。
myClass.h
:
class myClass {
std::string dataPath;
std::vector<double> data;
public:
myClass(std::string P = "./path/to/data-file.csv");
~myClass() {}
const double findPercentile(double percentile = 0.0);
}
编辑:从@FrançoisAndrieux提示,我已经修复了我的构造函数。
myClass.cpp
:
myClass::myClass(const std::string P) :
dataPath(P) {
// read data-sets into class member variables
}
有两个重要问题:
由于您使用的是gcc 4.8.5,因此请记住使用-std=c++11
标志,否则std::unique_ptr
将不可用。
在类定义的结尾加上;
。 声明类型时,C / C ++中必须使用分号。 因为您没有使用;
,您没有将myClass
声明为类型,因此它遵循以下行: static std::unique_ptr<myClass> classPtr;
由于myClass
不是有效的类型,将产生错误。
您对data
成员的初始化应为
data(std::vector<double>())
或更简单
data()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.