我正在尝试在Coeffs.cpp中设置一个静态变量:
#include "Coeffs.h"
class Coeffs
{
public:
double Coeffs::alpha5b = 0.0;
};
使用头文件
#ifndef COEFFS_H
#define GOEFFS_H
class Coeffs
{
public:
static double alpha5b;
};
#endif
使用以下代码:
#include <iostream>
#include <fstream>
#include <string>
#include "json/json.h"
#include "Coeffs.h"
using namespace std;
int main()
{
cout << "start" << endl;
string json;
ifstream inputStream;
inputStream.open("coeffTest.json");
inputStream >> json;
Json::Value root;
Json::Reader reader;
bool parseSuccess = reader.parse(json, root);
if(!parseSuccess)
{
cout << "failed" << endl;
}
else
{
Coeffs::alpha5b = 1.1;
//Coeffs::alpha5b = root.get("alpha5b", "NULL").asDouble();
//double item1[] = root.get("delta21b", "NULL").asDouble();
//cout << "alpha5b is: " << Coeffs::alpha5b << endl;
}
cout << "done" << endl;
}
但每次我编译我都会得到这个:
pottsie@pottsie:~/Documents/CoeffsJSON$ g++ -o JsonToCoeffs JsonToCoeffs.cpp -ljson_linux-gcc-4.6_libmt
/tmp/ccFxrr0k.o: In function `main':
JsonToCoeffs.cpp:(.text+0x10b): undefined reference to `Coeffs::alpha5b'
collect2: ld returned 1 exit status
我查看了一些其他类似的问题,无法找到有效的方法。我已经尝试添加构造函数并创建一个对象,但后来我仍然得到相同的错误。 谁知道该怎么办?
答案 0 :(得分:5)
类声明应放在标题(Coeffs.h)
中#ifndef COEFFS_H
#define COEFFS_H
class Coeffs
{
public:
static double alpha5b;
};
#endif
但是在源文件(.cpp,.cxx)中初始化静态成员:
#include "Coeffs.h"
double Coeffs::alpha5b = 0.0;
答案 1 :(得分:3)
在你的Coeffs.cpp中:
#include "Coeffs.h"
double Coeffs::alpha5b = 0.0;