C++ 是否初始化结构类型的静态变量?
首先,我只记录了电压样本、电流样本和能量样本: 然后我需要添加多个样本。我不擅长C++,但是我猜想一个好的方法是把上面的三个变量抛到一个结构中,然后初始化所说的Stut.的多个静态变量。 这是我最好的尝试:C++ 是否初始化结构类型的静态变量?,c++,C++,首先,我只记录了电压样本、电流样本和能量样本: 然后我需要添加多个样本。我不擅长C++,但是我猜想一个好的方法是把上面的三个变量抛到一个结构中,然后初始化所说的Stut.的多个静态变量。 这是我最好的尝试: struct recording { QList<qreal> voltageSamples; QList<qreal> currentSamples; QList<qreal> energySamples; }; static
struct recording {
QList<qreal> voltageSamples;
QList<qreal> currentSamples;
QList<qreal> energySamples;
};
static recording r1;
r1.voltageSamples = {3091, 3085, 2911, 3048};
r1.currentSamples{
4152956, 5341953, 7330711, 3425060,
5382685, 9864420, 6313012, 3024116,
6382968, 4411640, 7584845, 9992644,
9541896, 7608791, 7332224, 3368969
};
r1.energySamples{
8.914435413888887e-07, 2.038108591597222e-06, 3.611666070833333e-06, 4.346864713888889e-06,
5.500030215625000e-06, 7.613345194791666e-06, 8.965820335069444e-06, 9.613695186458332e-06,
1.090402989812500e-05, 1.179585517868056e-05, 1.332915266444444e-05, 1.534919340638889e-05,
1.736889472638889e-05, 1.897942215472222e-05, 2.053140956805556e-05, 2.124450800638889e-05
};
static recording r2;
...
但是我的代码不起作用。我做错了什么?您从初始化切换到赋值,但试图继续使用初始化语法。那是不可能的 如果将=in添加到currentSamples和energySamples中,那么这些赋值可能是有效的。我对QList的设计了解不够,无法确定是否确实如此,但这并不重要,因为,请参见下文 此外,您的赋值只是在空白空间中自由浮动,但此类语句/操作必须位于函数中,例如main 最后,您真的应该为类似的东西使用数组,而不是一堆编号的变量。如果你使用数组,那么你可以使用初始化器
static QList<qreal> voltageSamples[] = {
{3091, 3085, 2911, 3048},
{ /*(next sample data)*/ }
};
static QList<qreal> currentSamples[] = {
{
4152956, 5341953, 7330711, 3425060,
5382685, 9864420, 6313012, 3024116,
6382968, 4411640, 7584845, 9992644,
9541896, 7608791, 7332224, 3368969
},
{ /*(next sample data)*/ }
};
<> P>这里的关键是初始化者可以嵌套。 Worth,注意到C++ 20最终会带来C++……阿空加瓜山正在想是否有人会提出来!是的,应该让这个可怕的语法更清晰一些。
static QList<qreal> voltageSamples[] = {
{3091, 3085, 2911, 3048},
{ /*(next sample data)*/ }
};
static QList<qreal> currentSamples[] = {
{
4152956, 5341953, 7330711, 3425060,
5382685, 9864420, 6313012, 3024116,
6382968, 4411640, 7584845, 9992644,
9541896, 7608791, 7332224, 3368969
},
{ /*(next sample data)*/ }
};
static recording recordings[] = {
{ // recording 1
{3091, 3085, 2911, 3048}, // voltage samples
{ // current samples
4152956, 5341953, 7330711, 3425060,
5382685, 9864420, 6313012, 3024116,
6382968, 4411640, 7584845, 9992644,
9541896, 7608791, 7332224, 3368969
},
{ // energy samples
8.914435413888887e-07, 2.038108591597222e-06, 3.611666070833333e-06, 4.346864713888889e-06,
5.500030215625000e-06, 7.613345194791666e-06, 8.965820335069444e-06, 9.613695186458332e-06,
1.090402989812500e-05, 1.179585517868056e-05, 1.332915266444444e-05, 1.534919340638889e-05,
1.736889472638889e-05, 1.897942215472222e-05, 2.053140956805556e-05, 2.124450800638889e-05
}
},
{ // recording 2
/* etc */
}
};