gpt4 book ai didi

c++ - 如何在另一个类中设置静态变量?

转载 作者:太空狗 更新时间:2023-10-29 23:51:23 26 4
gpt4 key购买 nike

我试图在 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

我查看了其他一些类似的问题,但找不到任何有效的方法。我试过添加一个构造函数并创建一个对象,但我仍然遇到同样的错误。有人知道该怎么办吗?

最佳答案

类声明应该放在头文件中(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;

关于c++ - 如何在另一个类中设置静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21575824/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com