让我们假设,Bob将他的库包装到命名空间"bob"中,并且Alice将通过单个"using namespace bob"使整个命名空间在她自己的函数内可见,而不是每个单独使用"使用bob :: XYZ"项目:
// This file is written by Alice:
#include <iostream>
// She uses Bobs library:
#include "bob.hpp"
int main(void) {
// Import Bobs library and use it:
using namespace bob;
unsigned short value = 50000;
bob::dump_as_signed(value);
// Should not be possible without std:: prefix:
cout << "foobar" << endl;
}
Run Code Online (Sandbox Code Playgroud)
另一方面,Bob试图通过将实现包装在虚拟命名空间中来防止这种情况,并且仅使这些符号可用,这些符号适用于其他用户:
// This file is written …Run Code Online (Sandbox Code Playgroud)