gpt4 book ai didi

c++ - 变量不能出现在常量表达式中

转载 作者:太空宇宙 更新时间:2023-11-04 12:06:04 25 4
gpt4 key购买 nike

我很难弄清楚为什么 GCC 4.5 不允许我编译它:

#include <iostream>
#include <bitset>

#define WIDTH 512
#define HEIGHT 512

#define CEIL_POS(X) ((X - (unsigned int)(X)) > 0 ? (unsigned int)(X + 1) : (unsigned int)(X))

int main ()
{
const unsigned int length = static_cast<const unsigned int>(CEIL_POS(static_cast<float>(WIDTH * HEIGHT) / 8.0));

std::bitset<length> bits;

return 0;
}

它在 VS2010 中工作得很好。我错过了什么?

更新:我很匆忙,没有粘贴整个代码。对不起:(

PS:正如标题所说,我收到的错误是:“length cannot appear in a constant-expression.”

最佳答案

我不知道你遇到的问题是否是由编译器中的错误引起的,或者这是否是预期的行为,但简单地将 static_cast 移除为 float 似乎可以解决问题,并且结果完全相同值(value)。

#include <iostream>
#include <bitset>

#define WIDTH 512
#define HEIGHT 512

#define CEIL_POS(X) ((X - (unsigned int)(X)) > 0 ? (unsigned int)(X + 1) : (unsigned int)(X))

int main ()
{
const unsigned int length_1 = static_cast<const unsigned int>(CEIL_POS(static_cast<float>(WIDTH * HEIGHT) / 8.0));
const unsigned int length_2 = static_cast<const unsigned int>(CEIL_POS(WIDTH * HEIGHT / 8.0));

std::cout << length_1 << '\n' << length_2 << '\n';
if (length_1 == length_2)
std::cout << "They are exactly the same.";

std::bitset<length_2> bits;
}

关于c++ - 变量不能出现在常量表达式中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12030346/

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