为什么使用指令的范围会有所不同

Why does scope of using directive make a difference?

本文关键字:范围 有所不同 指令 为什么      更新时间:2023-10-16

下面是两个简化的代码示例:第一个编译得很好,第二个发出编译错误(找不到使用左手运算符ByteVector的运算符<<…)

这两个示例之间的唯一区别是using指令的位置。

我不想知道它为什么失败(你没有足够的信息来回答这个问题),我只感兴趣的是它为什么会在我放置using的地方产生任何的差异。

我本以为这两个例子都会有完全相同的行为。

编译无错误

ByteVector Test()
{
   using Base::operator <<;
   ByteVector foo;
   int bar = 1;
   foo << bar;
   return foo;
}

编译时出错

using Base::operator <<;
ByteVector Test()
{
   ...same as above, without using
}

额外信息:

运算符<lt;使用的定义如下

template<typename T>
ByteVector& operator<<(ByteVector &, const T&){...};

我唯一想到的就是Visual Studio。如果是这种情况,您可能希望将using指令放在相应的#include之后。正如页面上的评论所说:

将using指令放在源代码文件的开头使用IntelliSense降低意外行为的可能性。

否则,应该不会有什么不同。