C++入门(1):命名空间,IO流 输入输出,缺省参数
一、命名空间
1.1 命名空间的作用:
避免标识符命名冲突
1.2 命名空间定义:
关键字:namespace
namespace test
{// 命名空间内可以定义变量/函数/类型int a = 10;int Add(int x, int y){return x + y;}struct Stack{int* a;int top;int capacity;}// ... namespace test1{// ...}
}
PS:
-
命名空间可以嵌套.
-
在同一工程中,编译器会把相同名称的命名空间合并成到同一个命名空间中。
1.3 命名空间的使用
一个命名空间相当于定义了一个作用域,其中的所有内容局限在该命名空间中。
命名空间使用的三种方法:
// 1. 引入命名空间
using namespace test;// 2. 引入命名空间中的某个成员
using test::a;// 3. 使用作用域限定符 ::
printf("%d\n", test::a);
二、C++输入、输出
#include <iostream>// std 为C++标准库的命名空间
using std::cout; // cout 标准输出对象
using std::cin; // cin 标准输入对象
using std::endl; // endl 换行符int main()
{int a;double b;// >> 流提取cin >> a >> b;// << 流插入cout << a << endl << b << endl;return 0;
}
三、缺省参数
3.1 缺省参数概念
缺省参数是,在声明或定义函数时为函数的参数指定一个缺省值,在调用该函数时,如果没有指定实参则采用该形参的缺省值。
#include <iostream>
using namespace std;void Func(int a = 0)
{cout << a << endl;
}int main()
{Func();Func(20);return 0;
}