我有以下数组:
static std::pair<const Type, const size_t> typemap_[];定义为
std::pair<const talos::Message::Type, const size_t> talos::Message::typemap_[8] = {
{ talos::Message::Type::Empty, typeid(int).hash_code() },
{ talos::Message::Type::Keyboard , typeid(int).hash_code() },
...为什么这个
sizeof(typemap_);给出编译时错误
错误C2070‘std::对[]':非法操作数
即使这个
sizeof(typemap_[0]);数组的大小是固定的,是否合法?
类型定义为:
enum class Type {...} 发布于 2018-04-05 09:47:37
编译器似乎缺少typemap_变量的定义。因为它是静态的,所以它可能隐藏在其中一个源文件中。
如果你把你现在拥有的所有东西都放在同一个源中,那么解决方案就会奏效。例如:
enum class Type {None, Some} ;
static std::pair<const Type, const size_t> typemap_[] = {
{ Type::None, typeid(int).hash_code() },
{ Type::Some , typeid(int).hash_code() },
};
int main() {
std::cout << "sizeof: " << sizeof(typemap_) << " " << sizeof(typemap_[0]);
return 0;
}工作良好,输出sizeof: 32 16。
同时,一个元素的sizeof也是合法的,因为编译器知道数组的组成,即使不知道它的实际大小。
发布于 2018-04-05 09:43:54
如果在当前的翻译单元中没有static std::pair<const Type, const size_t> typemap_[];的定义,而只有这个声明,那么编译器就不可能知道它的大小,因为声明中没有大小。
发布于 2018-04-05 09:50:00
首先创建一个可重复的示例:
static char c[];
char c[8] = "";
int main()
{
return sizeof c;
}嗯,这甚至不会编译,因为我们不能声明c是静态的和不完整的:
49668931.cpp:1:13: error: storage size of ‘c’ isn’t known
static char c[];
^将其更改为extern,就可以了:
extern char c[];
char c[8] = "";
int main()
{
return sizeof c;
}但是,如果我们在c完成之前就需要它的大小,那么当然它会失败:
extern char c[];
int main()
{
return sizeof c;
}
char c[8] = "";49668931.cpp:5:19: error: invalid application of ‘sizeof’ to incomplete type ‘char []’
return sizeof c;
^https://stackoverflow.com/questions/49668931
复制相似问题