使用 memset 函数时对数组的引用是不明确的错误

问题描述 投票:0回答:3

我不明白为什么我会犯这个“奇怪”的错误。我读过类似的问题,但它没有回答我的问题。如果我在主函数而不是全局范围内定义数组,则不会出现错误。但假设我必须在全局范围内定义这个数组。为什么我会犯这个错误? 这是代码:

#include <iostream>
#include <cstring>

using namespace std;

int right[1005];
int main()
{
    memset(right,0,sizeof(right));
return 0;
}

这是错误:

memset2.cpp: In function ‘int main()’:
memset2.cpp:9:9: error: reference to ‘right’ is ambiguous
  memset(right,0,sizeof(right));
     ^
memset2.cpp:6:5: note: candidates are: int right [1005]
 int right[1005];
     ^
In file included from /usr/include/c++/4.8/ios:42:0,
             from /usr/include/c++/4.8/ostream:38,
             from /usr/include/c++/4.8/iostream:39,
             from memset2.cpp:1:
/usr/include/c++/4.8/bits/ios_base.h:924:3: note:                 std::ios_base& std::right(std::ios_base&)
   right(ios_base& __base)
   ^
memset2.cpp:9:24: error: reference to ‘right’ is ambiguous
  memset(right,0,sizeof(right));
                    ^
memset2.cpp:6:5: note: candidates are: int right [1005]
 int right[1005];
     ^
In file included from /usr/include/c++/4.8/ios:42:0,
             from /usr/include/c++/4.8/ostream:38,
             from /usr/include/c++/4.8/iostream:39,
             from memset2.cpp:1:
/usr/include/c++/4.8/bits/ios_base.h:924:3: note:                 std::ios_base& std::right(std::ios_base&)
   right(ios_base& __base)
   ^
c++ namespaces name-lookup using-directives unqualified-name
3个回答
7
投票

命名空间

std
已经有了名称
right
并且您通过指令
在全局命名空间中包含了 
std

形式的名称
using namespace std;

因此,为了避免歧义,请使用限定名称

memset( ::right, 0, sizeof( ::right ) );

或者删除该指令,在这种情况下,您可以使用非限定名称

right
,因为编译器将仅在全局命名空间中查找名称。


1
投票

从代码中删除

using namespace std ;
并在任何标准函数或对象之前加上
std::


0
投票

如果以下语句有歧义错误

memset ( (char*)&mybuf, 0, sizeof(mybuf) );

通过前面的 memset 来尝试一下

std::memset ( (char*)&mybuf, 0, sizeof(mybuf) ); 达里巴塞特

© www.soinside.com 2019 - 2024. All rights reserved.