gpt4 book ai didi

c++ - 为什么来自常量 POD 对象的字段本身不是常量?

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

我想为某个 GUID 专门化一个模板,它是一个 16 字节的结构。 GUID 对象有内部链接,所以我不能使用对象本身的地址,但我想我可以使用对象的内容,因为对象是一个常量。但这不起作用,如示例代码所示:

struct S
{
int const i;
};
S const s = { 42 };
char arr[s.i];

如果 s 是常数,为什么 s.i 不是常数?任何解决方法?

最佳答案

struct s 的初始化可以在运行时发生。但是,数组的大小必须 在编译时已知。编译器(当然)不会知道 s.i 的值在编译时是已知的,所以它只会看到您正在将变量用于不应该的东西。问题不在于常量,而是何时需要数组大小的问题。

您可能误解了const 的含义。它仅表示变量初始化后,它永远不会更改。例如这是合法的:

void func(int x){
const int i = x*5; //can't be known at compile-time, but still const
//int array[i]; //<-- this would be illegal even though i is const
}

int main(){
int i;
std::cin >> i;
func(i);
return 0;
}

为了绕过这个限制,在 C++11 中你可以将它标记为 constexpr 以指示该值可以在编译时确定。这似乎是你想要的。

struct S
{
int const i;
};
int main(){
constexpr S const s = { 42 };
char arr[s.i];
return 0;
}

编译:

$ c++ -std=c++11 -pedantic file.cpp


在 C99 中,你所做的是合法的,数组的大小不需要在编译时知道。

struct S
{
int const i;
};
int main(){
struct S const s = { 42 };
char arr[s.i];
return 0;
}

编译:

$ cc -std=c99 -pedantic file.c

关于c++ - 为什么来自常量 POD 对象的字段本身不是常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15392553/

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