2011-03-09 53 views
2

我是编程初学者,我经常看到很多程序使用前缀std,如果他们使用的任何std功能,如std::cout,std::cin等我想知道它是什么目的?这只是一种好的编程方式,还是更多的呢?它对编译器有什么区别,或者它是可读性还是什么?谢谢。什么是指定“STD”前缀的需要?

+4

因为你的程序将无法不把它编译? – 2011-03-09 00:03:54

+2

另见:http://stackoverflow.com/questions/2218140/what-requires-me-to-declare-using-namespace-std – 2011-03-09 00:05:20

回答

10

的STL的类型和功能在名为std的命名空间中定义。该std::前缀用于使用的类型,而完全包括std命名空间。

选项1(使用前缀)

#include <iostream> 

void Example() { 
    std::cout << "Hello World" << std::endl; 
} 

选项#2(使用的命名空间)

#include <iostream> 
using namespace std; 

void Example() { 
    cout << "Hello World" << endl; 
} 

选项#3(使用单独的类型)

#include <iostream> 
using std::cout; 
using std::endl; 

void Example() { 
    cout << "Hello World" << endl; 
} 

注:有一种包括整个C++命名空间(选项#2)以外的不具有前缀每种类型/方法其他含义std::文件(特别是如果一个报头内完成)。许多C++程序员避免这种做法,更喜欢#1或#3。

+1

@Erik那是另一种选择我elluded来。我会明确指出 – JaredPar 2011-03-09 00:08:15

+0

我会指出,你不应该在头文件中包含整个名称空间。它也会包含在用户的源代码中(包括你的头文件),这不是你想要的。 – 2011-03-09 00:21:04

+0

@Dadam,我的回答的最后一段指出它的#2不应该在头 – JaredPar 2011-03-09 00:36:28

0

这是短期的标准命名空间。

你可以使用:

using namespace std 

,如果你不想使用std ::法院,以保持和只使用COUT

+0

我不同意这里。 'std ::'优于'using namespace std'' – Tim 2011-03-09 00:09:40

+0

如果你“通常”使用它,请停止。见@埃里克的答案。 – 2011-03-09 00:11:41

+0

好吧,“通常”不是正确的用词。改变它意味着我的意思。 – Steve 2011-03-09 00:12:10

12

C++有命名空间的概念。

namespace foo { 
    int bar(); 
} 

namespace baz { 
    int bar(); 
} 

这两个函数可以在没有冲突的情况下共存,因为它们位于不同的名称空间中。

大部分的标准库函数和类生活在“STD”命名空间。要访问例如COUT,你需要做以下操作之一,按优先顺序:

  • std::cout << 1;
  • using std::cout; cout << 1;
  • using namespace std; cout << 1;

你应该避免using理由证明上述foo和巴兹命名空间。如果您有任何using namespace foo; using namespace baz;试图调用bar()将是不明确的。使用命名空间前缀是明确和详细的,有良好的习惯。

1

这是一个C++特征称为名称空间:

namespace foo { 
    void a(); 
} 


// ... 

foo::a(); 

// or: 

using namespace foo; 
a(); // only works if there is only one definition of `a` in both `foo` and global scope! 

的优点是,可以存在名为a多种功能 - 只要它们是不同的命名空间中的,它们可以被明确地使用(即foo::a()another_namespace::a() )。整个C++标准库位于std用于这一目的。

使用using namespace std;避免前缀,如果你能忍受的缺点(名称冲突,不太清楚其中的功能所属的...)。

2

没有人在他们的答案,一个using namespace foo语句可以在函数体内放提到的,从而减少了在其他范围内的命名空间的污染。

例如:

// This scope not affected by using namespace statement below. 

void printRecord(...) 
{ 
    using namespace std; 
    // Frequent use of std::cout, io manipulators, etc... 
    // Constantly prefixing with std:: would be tedious here. 
} 

class Foo 
{ 
    // This scope not affected by using namespace statement above. 
}; 

int main() 
{ 
    // This scope not affected either. 
} 

你甚至可以把一个using namespace foo声明局部范围(对花括号)内。