目录
C到C++
头文件
C风格
C++风格
输入输出
输出
输入
命名空间
作用
创建
使用
::作用域限定符
名字空间声明
名字空间指令
命名空间合并
声明和定义分开
命名空间嵌套
命名空间别名
C到C++
01
头文件
C风格
#include<stdio.h>
#include<math.h>
C++风格
#include<iostream>
#include<cstdio> //C++风格
#include<cmath> //math.h cmath
02
输入输出
::作用域限定符
#include<iostream>
using namespace std; //命名空间 名字空间
int main()
{
std::cout << "hello world" << std::endl;
return 0;
}
名字空间声明
using 名字空间::成员
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
namespace DeRoy
{
void fun()
{
cout << "我是DeRoy的fun函数" << endl;
}
}
using DeRoy::fun;//DeRoy空间里面的fun函数全局可见
int main()
{
cout << "hello world" << endl;
fun(); //调用fun函数
return 0;
}
名字空间指令
using namespace 名字空间
#include<iostream>
using namespace std; //命名空间 名字空间
namespace DeRoy
{
void fun()
{
cout << "我是DeRoy的fun函数" << endl;
}
}
using namespace DeRoy;
int main()
{
std::cout << "hello world" << std::endl;
fun();
return 0;
}
命名空间合并
#include<iostream>
using namespace std; //命名空间 名字空间
namespace DeRoy
{
void fun()
{
cout << "我是DeRoy的fun函数" << endl;
}
}
namespace DeRoy //命名空间合并 同名空间合并
{
void test()
{
cout << "我是DeRoy的test函数" << endl;
}
}
int main()
{
DeRoy::fun();
DeRoy::test();
return 0;
}
声明和定义分开
#include<iostream>
using namespace std; //命名空间 名字空间
namespace DeRoy //命名空间合并 同名空间合并
{
void test();
}
void DeRoy::test() //命名空间成员函数 声明和定义分开
{
cout << "我是DeRoy的out函数" << endl;
}
int main()
{
DeRoy::test();
return 0;
}
命名空间嵌套
//命名空间嵌套
namespace ShanXi
{
namespace XiAn
{
namespace ChangAn
{
void SchoolName()
{
cout << "西北工业大学" << endl;
}
}
}
}
命名空间别名
namespace Changan = ShanXi::XiAn::ChangAn;
思维导图:
#include<stdio.h>
#include<iostream>
using namespace std; //命名空间 名字空间两种叫法
int main()
{
//输出
printf("hello world\n");
cout << "hello world" << endl; //endl endline换行
//输入
int num;
scanf("%d", &num);
cin >> num;
system("pause");
return 0;
}