1、在 C++ 中,分号是语句结束符,每个语句必须以分号结束。
2、语句块是一组使用大括号括起来的按逻辑连接的语句。
{
cout << "Hello World"; // 输出 Hello World
return 0;
}
3、C++标准库
C++标准库是C++编程语言的一个组成部分,提供了一系列的类和函数,旨在支持广泛的编程任务。其包括, 1)输入输出流(I/O); 2)容器,如vector
、list
、map
等; 3)算法,如排序、搜索、复制等; 4)字符串处理,string
类; 5)等等;
std
命名空间是C++标准库中所有标识符(如函数、类、对象等)所属的命名空间。命名空间是一种封装机制,用于组织和隔离代码中的名称,防止命名冲突的发生。在C++中,命名空间是解决不同库之间名称可能重叠的一种方法。
以下列举三种使用标准库里相关功能的用法:
(1)引用标准库中的名称时加上 std::
前缀
如 std::cout
和 std::vector
#include <iostream>
#include <vector>
int main() {
std::cout << "Hello, World!" << std::endl;
std::vector<int> myVector;
myVector.push_back(10);
return 0;
}
(2)使用 using namespace std;
指令
在文件开头添加指令,cout前就不用加 std:: 前缀
#include <iostream>
#include <vector>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
vector<int> myVector;
myVector.push_back(10);
return 0;
}
(3)只引用需要的标准库名称
例如现在只需要用到 cout、endl和vector这三个名称,可以单独引用
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
int main() {
cout << "Hello, World!" << endl;
vector<int> myVector;
myVector.push_back(10);
return 0;
}
这种做法有助于减少潜在的命名冲突。当然,这些问题只会出现在程序变得更大,或者你开始使用多个库时,如果两个不同的命名空间中有相同的名称,就会产生歧义。这种情况暂时不会遇到,先不考虑。