C++中的输入、输出、换行符
cin cout endl的定义以及使用
cin cout endl这些对象都是由C++提供定义的,我们在使用时,只需要将定义和声明
部分引用到自己工程即可。
extern ---- 外部声明,它告诉编译器,这个变量是在其他地方定义,这个地方告诉编译
器是一个外部声明
extern istream cin; /// Linked to standard input
extern ostream cout; /// Linked to standard output
它们被定义在std命名空间中
namespace std
{
extern istream cin; //输入,相当于C语言中的scanf
extern ostream cout; //输出,相当于C语言中的printf
}
std及istream和ostream他们都间接引入#include <iostream>
所以在使用时,必须要包含该文件中,对于using namespace std;是可选的
1.命名空间(namespace)
作用:解决在开发过程中,全局变量名冲突的问题。
图例说明:
1.1如何定义一个命名空间:
//语法:
// namespace 空间名
// {
// //空间中的成员,参、变量、函数、结构体。。。。。
// }
namespace XD
{
char name[1024] = {"小明"};
float height = 172.5 ;
int age = 23;
}
1.2如何访问命名空间里面的成员?
命名空间中的成员的访问方法主要有三种:
代码示例:
#include <iostream>
using namespace std; //把std空间里的所有数据暴露出来
// namespace XD
// {
// char name[1024] = {"小明"};
// float height = 172.5 ;
// int age = 23;
// }
// int main ()
// {
// //指std定命名空间,指定XD命名空间
// std::cout << XD::name << std::endl;
// std::cout << XD::height << std::endl;
// std::cout << XD::age << std::endl;
// }
namespace XD //定义一个命名空间
{
char name[1024] = {"小明"};
float height = 172.5 ;
int age = 23;
}
//方法一:在访问时通过域操作符:: 指定命名空间。
// cout << XD::height << endl; //指定命名空间
//方法二:使用using关键字,把整个命名空间暴露出来。
// using namespace XD;
//方法三:使用using关键字,把指定的命名空间中的成员暴露出来。
using XD::age;
int main ()
{
// cout << name << endl; //使用方法一访问
// cout << XD::height << endl; //使用方法二访问
cout << age << endl; //使用方法三访问
}
1.3关于命名空间的嵌套
代码例子:
#include <iostream>
using namespace std; //把std空间里的所有数据暴露出来
namespace XD
{
namespace X
{
char name[1024] = {"小明"};
float height = 172.5 ;
int age = 23;
void show()
{
cout << "你好,我好才是真的好" << endl;
}
}
}
using namespace XD; //方法二:使用using namespace XD把命名空间暴露出来
int main ()
{
cout << XD::X::name << endl;//嵌套了多少层就要剥开多少层
cout << X::name << endl; //等价于cout << XD::X::name << endl;
XD::X::show(); //如果嵌套函数,也是一样
return 0;
}