求教个简单的 C++ 语法问题

184 天前
 Betsy

代码如下

#include<iostream>

enum ExprValueType : uint8_t {
  MinInf = 1
};

int main(int argc, char* argv[]) {
  ExprValueType type = MinInf;
  std::cout <<"Hello world" << std::endl;
  std::cout << type << std::endl;
  return 0;
}

使用 g++ abc.cc -o a.out -std=c++20 报错,报错信息如下所示

abc.cc:3:20: error: found ‘:’ in nested-name-specifier, expected ‘::’
    3 | enum ExprValueType : uint8_t {
      |                    ^
      |                    ::
abc.cc:3:6: error: ‘ExprValueType’ has not been declared
    3 | enum ExprValueType : uint8_t {
      |      ^~~~~~~~~~~~~
abc.cc:3:30: error: expected unqualified-id before ‘{’ token
    3 | enum ExprValueType : uint8_t {
      |                              ^
abc.cc: In function ‘int main(int, char**)’:
abc.cc:8:3: error: ‘ExprValueType’ was not declared in this scope
    8 |   ExprValueType type = MinInf;
      |   ^~~~~~~~~~~~~
abc.cc:10:16: error: ‘type’ was not declared in this scope; did you mean ‘std::__cmp_cat::type’?
   10 |   std::cout << type << std::endl;
      |                ^~~~
      |                std::__cmp_cat::type
In file included from /usr/include/c++/13/bits/char_traits.h:56,
                 from /usr/include/c++/13/ios:42,
                 from /usr/include/c++/13/ostream:40,
                 from /usr/include/c++/13/iostream:41,
                 from abc.cc:1:
/usr/include/c++/13/compare:49:11: note: ‘std::__cmp_cat::type’ declared here
   49 |     using type = signed char;
      |           ^~~~

个人猜测是 gcc 版本的问题,于是在 https://gcc.godbolt.org/ 切换不同的编译器查看。


于是产生了两个困惑

1354 次点击
所在节点    C++
9 条回复
xipuxiaoyehua
184 天前
enum class ExprValueType : uint8_t {
MinInf = 1
};
Betsy
184 天前
@xipuxiaoyehua 不可以的,从 Unscoped enumerations 换成 Scoped enumerations 依然存在这个问题。
geelaw
183 天前
因为标准规定 std::uint8_t 在 cstdint 中定义。请注意直接用 uint8_t 也是错误的,能编译通过只是因为运气好。

之前在 #include <iostream> 之后看起来可以用,大概是因为:

1. 具体实现里的 iostream 间接包含了 cstdint ;且
2. 具体实现里的 cstdint 也在全局命名空间里定义了 uint8_t 。

这两件事不是必然成立,所以编译失败不稀奇。
marat1ren
183 天前
感觉是需要 cstdint 里面定义的 uint8_t 。可以试试 std::unit8_t
Betsy
183 天前
@geelaw 这样子啊,感谢说明 🙏
dangyuluo
183 天前
dangyuluo
183 天前
缺 uint8_t
Betsy
183 天前
@marat1ren
@dangyuluo

是的。经过确认不引入 cstdint ,直接 std::uint8_t 是不可以的
Betsy
183 天前
@dangyuluo 这个改动实在太骚气了 😅

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/989690

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX