【问题标题】:redefine uint type c++重新定义 uint 类型 c++
【发布时间】:2017-10-07 18:22:38
【问题描述】:

在c++ 中,当我尝试编译以下代码时,我得到一个冲突的声明错误:

#include <iostream>
using namespace std;

typedef uint_least64_t uint;

int main() {
    uint i = -1;
    cout << i << endl;
}

错误:

main.cpp:5:24: error: conflicting declaration ‘typedef uint_least64_t uint’
 typedef uint_least64_t uint;
                        ^~~~
In file included from /usr/include/stdlib.h:275:0,
                 from /usr/include/c++/6/cstdlib:75,
                 from /usr/include/c++/6/ext/string_conversions.h:41,
                 from /usr/include/c++/6/bits/basic_string.h:5417,
                 from /usr/include/c++/6/string:52,
                 from /usr/include/c++/6/bits/locale_classes.h:40,
                 from /usr/include/c++/6/bits/ios_base.h:41,
                 from /usr/include/c++/6/ios:42,
                 from /usr/include/c++/6/ostream:38,
                 from /usr/include/c++/6/iostream:39,
                 from main.cpp:1:
/usr/include/x86_64-linux-gnu/sys/types.h:152:22: note: previous declaration as ‘typedef unsigned int uint’
 typedef unsigned int uint;
                      ^~~~

我认为冲突的声明错误是因为 uint 的类型声明已经存在于语言中的某处,并且我相信该类型是 uint_least32_t 因为:

#include <iostream>
using namespace std;

int main() {
    uint i = -1;
    cout << i << endl;
}

返回一个整数值,即 (2^32)-1。因此c++ 中是否可以将uint 重新定义为uint_least64_t。

【问题讨论】:

  • 显示其余代码。
  • 问题已被编辑。如果您需要任何其他信息,请告诉我。

标签: c++ c++11


【解决方案1】:

从错误消息中可以看出,在您的平台上&lt;iostream&gt; 拉入&lt;string&gt;,拉入&lt;cstdlib&gt;,拉入&lt;stdlib.h&gt;,拉入&lt;sys/types.h&gt;。

查看源码,我们可以看到&lt;sys/types.h&gt;是这样做的:

#ifdef __USE_MISC
/* Old compatibility names for C types.  */
typedef unsigned long int ulong;
typedef unsigned short int ushort;
typedef unsigned int uint;
#endif

#ifdef __USE_MISC 守卫是feature_test_macros 系统的一部分。如果您请求 _DEFAULT_SOURCE,则会在内部设置 __USE_MISC(如果您没有其他请求,也会设置)。

因此,您应该能够通过使用-ansi 或-std=... 选项之一(例如-std=c++11)进行编译来绕过该问题。

【讨论】:

    【解决方案2】:

    uint 不是标准 C++ 的一部分。

    很有可能您的代码库中的某些东西正在引入它,或者甚至可能是您的编译器附带的 C++ 标准库。你可能很幸运,图书馆已经引入了std::uint,当你编写污染语句using namespace std;时,你正在将它引入全局命名空间。

    遗憾的是,一旦引入了 typedef 类型,您就不能取消它或隐藏 class。

    所以你只需要使用不同的符号。

    【讨论】:

    • “遗憾的是,一旦引入了类型,就不能取消 typedef 或隐藏类。”。我想这意味着我必须将 uint 的每个实例更改为 uint_least64_t 或 typedef
    • 啊,现在你粘贴了更多代码,你永远不知道,删除 using namespace std; 可能会解决它。
    • 很遗憾,它没有
    • 范围内的using 怎么样?你可以用它来替换命名空间中的typedef 吗?
    【解决方案3】:

    您不能重新定义 typedef 符号,必须使用不同的(未使用的)符号。

    如果您想使用相同的符号,可以将其包装在本文中提到的命名空间中:Using a typedef'd uint causes error, while "unsigned int" does not...?

    【讨论】:

      猜你喜欢
      • 2019-12-14
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多