C++入门
一、C++兼容C
C++
兼容C
语言的所有用法
#include<stdio.h>
int main()
{
printf("hello world\n");
return 0;
}
二、命名空间
在C/C++
中,变量、函数和后面要学到的类都是大量存在的,这些变量、函数和类的名称将都存在于全局作用域中,可能会导致很多冲突。使用命名空间的目的是对标识符的名称进行本地化,以避免命名冲突或名字污染,namespace
关键字的出现就是针对这种问题的
变量rand
和 库<stdlib.h>
里rand
函数命名冲突
#include<stdio.h>
#include<stdlib.h>
int rand = 0;
int main()
{
printf("%d\n",rand);
return 0;
}
C语言没办法解决类似这样的命名冲突问题,所以C++提出了namespace
来解决
2.1 命名空间的定义
namespace xq
{
....
}
定义命名空间,需要使用到namespace
关键字,后面跟命名空间的名字,然后接一对{}
即可,{}
中即为命名空间的成员。
- 命名空间不影响变量生命周期,只是限定域,编译查找规则
#include<stdio.h>
#include<stdlib.h>
namespace xq
{
int rand = 10;
}
void func()
{
printf("%p\n", rand);
printf("%d\n", xq::rand);
}
int main()
{
func();
printf("%p\n", rand);
printf("%d\n", xq::rand);
return 0;
}
查找规则默认:1. 先局部,再全局 2. 指定域里面找
局部变量,要建立栈帧
- 命名空间中可以定义变量、函数、类型
#include<stdio.h>
namespace xq
{
int rand = 1;
int Add(int a, int b)
{
return a+b;
}
struct Node
{
struct Node* next;
int val;
};
}
int main()
{
printf("%d\n", xq::Add(1, 2));
struct xq::Node node;
}
- 命名空间可以嵌套
#include<stdio.h>
namespace xq
{
int a = 1;
namespace xq_q
{
int b = 2;
}
}
int main()
{
printf("%d\n", xq::a);
printf("%d\n", xq::xq_q::b);
return 0;
}
- 同一个工程中允许存在多个相同名称的命名空间,编译器最后会合成同一个命名空间中。
//test.h
#pragma once
#include<stdio.h>
namespace xq
{
int a = 1;
}
//main.cpp
#include "test.h"
namespace xq
{
int b = 10;
}
int main()
{
printf("%d %d", xq::a, xq::b);
}
ps
:一个工程中的test.h
和上面main.cpp
中两个xq
会被合并成一个
2.2 命名空间的使用
2.2.1 域作用限定符
-
C++引入:
::
域作用限定符 -
::a
空白默认全局域
#include<iostream>
using namespace std;
int a = 1;
int main()
{
int a = 10;
cout << a << endl;
cout << ::a << endl;
return 0;
}
rand
放在命名空间是全局变量
2.2.2 命名空间三种使用方式
-
加命名空间名称及作用域限定符
例:
std::cout
域作用限定符
#include<iostream>
int main()
{
int a = 10;
std::cout << a <<std::endl;
return 0;
}
- 使用
using
将命名空间中某个成员引入
例:using namespace std
[注意]:日常练习可以这样使用,项目中不要这样使用,会把标准库全部暴露出来,如果我们定义跟库重名的类型、对象、函数,就存在冲突问题。
#include<iostream>
using namespace std;
int main()
{
int a = 10;
cout << a <<endl;
return 0;
}
- 使用
using namespace
命名空间名称引入
例:using std::cout
#include<iostream>
using std::cout;
using std::endl;
int main()
{
int a = 10;
cout << a << endl;
return 0;
}
二、C++输入\输出
每种语言都有独特的于这个世界问候的方式hello world!
C++
我们来看一下C++是如何来实现问候的
#include<iostream>
// std是C++标准库的命名空间名,C++将标准库的定义实现都放到这个命名空间中
using namespace std;
int main()
{
cout<<"Hello world!!!"<<endl;
return 0;
}
[说明]
- 使用
cout
标准输出对象(控制台)和cin
标准输入对象(键盘),必须包含头文件以及命名空间使用std
endl
是C++
特殊的符号,表示换行输出,等价于'\n'
,和cout
cin
一样包含在<iostream>
中
endl
~'\n'
#include<iostream>
using namespace std;
int main()
{
int a = 0;
cout << a << endl;
cout << a << '\n';
return 0;
}
<<
是流插入运算符,>>
是流提取运算符
cin cout
是对象 <<
>>
运算符重载,特点:自动识别类型
#include<iostream>
using namespace std;
int main()
{
int a;
double b;
char c;
cin >> a >> b;
cin >> c;
cout