CCG*_*CCG 0 c++ compilation forward-declaration
我一直在寻找我遇到的编译错误消息的答案,但我似乎我的用例更简单,并且这个问题甚至不应该存在.我当然缺少一些非常微不足道的东西,并希望找到错误的帮助.
我有以下代码片段.
/*file rand.h*/
class random{
// definition of class
};
Run Code Online (Sandbox Code Playgroud)
和另一个名为method.h的文件
/* file method.h*/
#include "rand.h"
/* lots of stuff...many lines */
class method{
random rng;
};
Run Code Online (Sandbox Code Playgroud)
最后一个cpp文件main.cpp
#include "method.h"
int main(){
method METHOD;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在编译时,我收到错误:
In file included from main.cpp:2:0:
method.h:40:5: error: ‘random’ does not name a type
random rng;
Run Code Online (Sandbox Code Playgroud)
method.h
#ifndef METHOD
#define METHOD
#include "rand.h"
class node
{
//stuff
};
// stuff
template<class T>
class ssa
{
public:
T& model;
random rng;
};
Run Code Online (Sandbox Code Playgroud)
rand.h
#ifndef RAND_H
#define RAND_H
#include "mtrand.h"
#include <cmath>
class random : public MTRand {
public:
MTRand rng;
random(){};
random(unsigned long seed){rng.seed(seed);};
void seed(unsigned long _seed){
rng.seed(_seed);
}
double exp(double theta){
double inv_mean = 1.0/theta;
double u = rng();
return std::log(1 - u)/(-inv_mean);
}
double uniform(){
return rng();
}
};
#endif
Run Code Online (Sandbox Code Playgroud)
model.h包含在主文件中.
使用该命令进行编译
g++ -c -fPIC main.cpp -o main.o
有一个叫做的POSIX函数random,声明在<stdlib.h>.您的班级名称似乎random与此相冲突.
最简单的解决方案是更改类的名称(您在评论中说,这有效).
由于random()函数由POSIX定义但不是由ISO C定义,并且在C标准头中声明,因此您也可以在严格的ISO符合模式下调用编译器.如果你正在使用gcc,gcc -std=cNN应该工作,其中NN的一个90,99或11.但这意味着你不能使用POSIX特定的功能,这可能是也可能不是问题.
将命名空间中的类包装起来可能是一个更清晰的解决方案(感谢Alexis Wilke提出的建议).