一.概念
1.第一个程序
#include <iostream> //标准的输入输出流
using namespace std; //声明了一个命名空间 cout 对象存在std作用域下
int main()
{
//cout 标准输出流
//endl 换行
cout << "hello world" << endl;
return 0;
}
2.面向对象编程的三大特点
封装:将属性和方法封装在一起抽象成一个类 ,并且对类中的成员加以权限控
继承:将一个类中属性和方法继承到另一个类中
多态:一个接口 对种形态 (静态多态 动态多态)
3.冒号作用域
:: 运算符是一个作用域,如果::前面什么都没有加,代表是全局作用域
#include <iostream>
using namespace std;
int a = 100;
void test01()
{
int a = 10;
cout << a << endl;//输出局部变量a
cout << ::a << endl;//输出全局变量a
}
int main()
{
test01();
return 0;
}
二.命名控制
1.命名空间
namespace:本质是作用域,可以更好的控制标识符的作用域
命名空间可以存放:变量 、函数 、类、结构体 ...
2.命名空间的使用
a.命令空间的定义:必须定义在全局范围
b.命名空间下可以存放 变量 函数 结构体 类
c.命名空间可以重名 重名的命名空间相当于做合并操作
d.命名空间可以嵌套命名空间
e.命名空间可以取别名, namespace newname = oldname;
f.命名空间可以没有名字 ,没有名字相当于给命名空间 内的所有成员加上了static修饰
g.命名空间中的函数可以先声明,在外部定义,定义时需要加上命名空间作用域
#include <iostream>
using namespace std;
/*
* 定义命名空间:必须定义在全局范围中
* 命名空间下可以存放:变量、函数、结构体、类
* 命名空间可以重名,重名的命名空间相当于做合并操作
* 命名空间可以嵌套命名空间
* 命名空间可以取别名, namespace newname = oldname;
* 命名空间可以没有名字 ,没有名字相当于给命名空间内的所有成员加上了static修饰
* 命名空间中的函数可以先声明,在外部定义,定义时需要加上命名空间作用域
*/
namespace A
{
int a = 100;
void full(int x);
void fun()
{
cout << "hello bit" << endl;
}
}
namespace A
{
int b = 200;
int c = 300;
}
namespace B
{
int a = 10;
}
namespace C
{
int a = 99;
namespace D
{
int a = 88;
}
}
void test02()
{
cout << "C:a=" << C::a << endl;
cout << "C:D:a=" << C::D::a << endl;
}
void test01()
{
cout << "A:a=" << A::a << endl;
cout << "B:a=" << B::a << endl;
A::fun();
cout << A::b << endl; //重名
}
void A::full(int x)
{
cout <<"A:full=" <<x << endl;
}
void test03()
{
A::full(999);
}
int main()
{
//test01();
//test02(); //嵌套
//test03();
return 0;
}
三.using的定义和使用
1.当using声明的标识符和其他标识符有作用域冲突时,会产生二义性
#include <iostream>
using namespace std;
namespace nameA
{
int a = 100;
void bit()
{
cout << "hello bit"<< endl;
}
}
void test01()
{
//注意:当using声明的标识符和其他标识符有作用域冲突时,会产生二义性
//int a = 100;
cout << "nameA:a=" << nameA::a << endl;
using nameA::a;
cout << "nameA:a=" << a << endl;
nameA::bit();
using nameA::bit;
bit();
}
int main()
{
test01();
return 0;
}
2.using的编译指令
using编译指令使整个命名空间标识可用,并且命名空间标识符如果和局部变量的标识符有冲突时,优先使用using编译指令
#include <iostream>
using namespace std;
namespace nameA
{
int a = 100;
void bit()
{
cout << "hello bit"<< endl;
}
}
void test02(){
//using编译指令使整个命名空间标识符可用
int a =1000;
using namespace nameA;
cout << "nameA:a=" << nameA::a << endl;
bit();
}
int main()
{
test02();
return 0;
}