在C ++中包含和使用命名空间 [英] include and using namespace in C++

查看:244
本文介绍了在C ++中包含和使用命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 cout ,我需要同时指定:

  #include< iostream> 

 c $ c> using namespace std; 

cout 在哪里定义?在 iostream ,正确吗?所以, iostream 本身就是在命名空间 std



关于使用 cout



的语句的含义是什么?

解决方案

iostream 是定义cout的文件的名称。
另一方面, std 是一个命名空间,等同于(在某种意义上)java包。



cout是在 iostream 文件中定义的实例,位于std命名空间内。



在另一个命名空间中可能存在另一个 cout 实例。因此,为了表示您要使用 std 命名空间中的 cout 实例,您应该写



std :: cout ,表示范围。

  std :: cout<<Hello world<< std :: endl; 

为了避免 std :: 可以使用使用子句。

  cout<世界<<< endl; 

它们是两个不同的东西。一个表示范围,另一个表示实际包括 cout



假设在iostream中,两个名为 cout 的实例存在于不同的命名空间中

 命名空间std {
ostream cout;
}
namespace other {
float cout; //另一个类型的实例。
}

包含< iostream> ,你仍然需要指定命名空间。 #include 语句没有说嘿,使用std ::中的cout。这是使用的用途,用于指定范围


for using cout, I need to specify both:

#include<iostream>

and

using namespace std;

Where is cout defined? in iostream, correct? So, it is that iostream itself is there in namespace std?

What is the meaning of both the statements with respect to using cout?

I am confused why we need to include them both.

解决方案

iostream is the name of the file where cout is defined. On the other hand, std is a namespace, equivalent (in some sense) to java's package.

cout is an instance defined in the iostream file, inside the std namespace.

There could exist another cout instance, in another namespace. So to indicate that you want to use the cout instance from the std namespace, you should write

std::cout, indicating the scope.

std::cout<<"Hello world"<<std::endl;

To avoid the std:: everywhere, you can use the using clause.

cout<<"Hello world"<<endl;

They are two different things. One indicates scope, the other does the actual inclusion of cout.

In response to your comment

Imagine that in iostream two instances named cout exist, in different namespaces

namespace std{
   ostream cout;
}
namespace other{
   float cout;//instance of another type.
}

After including <iostream>, you'd still need to specify the namespace. The #include statement doesnt say "Hey, use the cout in std::". Thats what using is for, to specify the scope

这篇关于在C ++中包含和使用命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆