2009-07-30 73 views
3
namespace A 
{ 
    #include <iostream> 
}; 

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

没有编译器吗? – 2009-07-30 02:20:53

+2

你为什么想这样做? – AraK 2009-07-30 02:24:03

回答

8

简短的回答:

龙答:嗯,不是真的。虽然你可以伪造它。您可以在外面声明并使用命名空间内的语句,像这样使用:

#include <iostream> 

namespace A 
{ 
    using std::cout; 
}; 

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

不能本地化库,因为即使它曾在一个访问,也不会在标准命名空间访问。另外,“另一个问题是名称空间内的限定名称将是A :: std :: cout,但该库不包含使用外部名称空间限定的名称。”谢谢Jonathon Leffler。

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

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; 
}

Thit方法被称为命名空间走样。以下示例显示该功能的真正目的:

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 
}
相关问题