3
namespace A
{
   #include <iostream>
};

int main(){
 A::std::cout << "\nSample";
 return 0;
}
4

2 回答 2

8

简短的回答:没有。

长答案:嗯,不是真的。不过,你可以伪造它。您可以在外部声明它并在命名空间内使用 using 语句,如下所示:

#include <iostream>

namespace A
{
   using std::cout;
};

int main(){
 A::cout << "\nSample";
 system("PAUSE");
 return 0;
}

您无法本地化库,因为即使它在 A 中具有访问权限,它也无法在标准命名空间中访问。

此外,“另一个问题是命名空间内的限定名称将是 A::std::cout,但库不包含外部命名空间限定的名称。” 感谢乔纳森·莱弗勒。

如果问题是您不想让其他人知道您的所有代码可以做什么,您可以拥有自己的 cpp 文件来包含 iostream,并在其中定义命名空间。然后你只需将它包含在 main (或其他)中,让程序员知道他能做什么和不能做什么。

于 2009-07-30T02:31:48.610 回答
5

你可以写:

#include <vector> // for additional sample
#include <iostream>
namespace A
{
  namespace std = std; // that's ok according to Standard C++ 7.3.2/3
};

// the following code works
int main(){
 A::std::cout << "\nSample"; // works fine !!!
 A::std::vector<int> ints;
 sort( ints.begin(), ints.end() );  // works also because of Koenig lookup

 std::cout << "\nSample";  // but this one works also
 return 0;
}

这种方法称为命名空间别名。以下示例显示了该功能的真正用途:

namespace Company_with_very_long_name { /* ... */ }
namespace CWVLN = Company_with_very_long_name;

// another sample from real life
namespace fs = boost::filesystem;
void f()
{
  fs::create_directory( "foobar" );   // use alias for long namespace name
}
于 2009-07-30T04:48:49.480 回答