代码C++01 C++书写HelloWorld02 双冒号作用域运算符03 namespace命名空间
原创
©著作权归作者所有:来自51CTO博客作者mb63816ca2ee95f的原创作品,请联系作者获取转载授权,否则将追究法律责任
#include <iostream> // 标准输入输出流 i -- input 输入 o -- output 输出 类似于stdio
using namespace std; //使用 标准 命名空间 打开一个房间
//#include <math.h>
//#include <cmath>
//
//#include <time.h>
//#include <ctime>
//程序入口函数
int main()
{
//cout 输出流对象 向屏幕中输出内容
// <<在C++中可以有新的意义 ,可以在cout后拼接想输出的内容
// endl 结束输入并且换行
// 不需要记 %d %s %c %f 格式化
// 对于换行 \n \r\n C++下 只需要记住 endl
cout << "hello world" << 12345 << endl;
system("pause"); //阻塞
return EXIT_SUCCESS;
}
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
int atk = 1000;
void test01()
{
int atk = 2000;
cout << "局部攻击力为: " << atk << endl;
//:: 作用域运算符 当::前面没有任何作用域情况下,代表使用全局作用域
cout << "全局攻击力为: " << ::atk << endl;
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include "game1.h"
#include "game2.h"
//1、命名空间 用途 解决命名冲突
void test01()
{
LOL::goAtk();
kingGlory::goAtk();
}
//2、命名空间下 可以存放 变量、函数、结构体、类....
namespace A
{
int m_A = 10;
void func(){};
struct Person
{
int age;
};
class Animal
{
int age;
};
}
//3、命名空间必须 声明下 全局作用域下
//void func()
//{
// namespace B
// {
//
// }
//}
//4、命名空间 可以 嵌套命名空间
namespace B
{
int m_A = 10;
namespace C
{
int m_A = 20;
}
}
void test02()
{
cout << "B空间下的m_A = " << B::m_A << endl;
cout << "C空间下的m_A = " << B::C::m_A << endl;
}
//5、命名空间是开放的,可以随时向命名空间下添加新的成员
namespace B
{
int m_B = 100;
}
void test03()
{
cout << "B空间下的m_A = " << B::m_A << endl;
cout << "B空间下的m_B = " << B::m_B << endl;
}
//6、命名空间是可以匿名的
namespace
{
int m_C = 100;
int m_D = 200;
//相当于 在变量前加了一个关键字 static
// static int m_C = 100;
// static int m_D = 200;
}
void test04()
{
cout << "m_D = " << ::m_D << endl;
}
//7、命名空间是可以起别名的
namespace veryLongName
{
int m_A = 1000;
}
void test05()
{
namespace veryShortName = veryLongName;
cout << veryShortName::m_A << endl;
cout << veryLongName::m_A << endl;
}
int main(){
//test01();
//test02();
//test03();
//test04();
test05();
system("pause");
return EXIT_SUCCESS;
}
#include "game1.h"
//LOL:: 代表 LOL作用域下的goAtk函数实现
void LOL::goAtk()
{
cout << "LOL的攻击实现" << endl;
}
#include "game2.h"
void kingGlory::goAtk()
{
cout << "王者农药的攻击实现" << endl;
}