命名空间
c++中为了命名空间的出现更好的解决了命名冲突,并且在使用时可以更加的清晰了解到函数的来源和出处,相比于c语言中的处理函数名字冲突的状况,c++的命名空间使得代码的可读性更高,使用和规则简洁,但是在使用时应当尽量避免全局使用using namespace和在头文件使用using namespace 因为这会使得你在调用头文件时会增加代码的不确定性在使用using namespace时要尽量缩小起使用域,不然就会破坏其提供的便捷能力。本质上来说类也是一种命名空间,所以也可以拿class来定义函数使用。
语法:”namespace 名称{代码块}“ 或”namespace 名称{namespace 名称{代码块}}“(可以一直嵌套)
调用时语法:空间名字::函数名
使用示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #include <iostream> #include <string> #include <algorithm>
namespace example1 { void Print() { std::cout << "hello" << std::endl; } }
namespace example2 { namespace inner { void Print() { std::cout << "This is another function!" << std::endl; } } }
int main() { example1::Print(); example2::inner::Print(); using namespace example2::inner; Print(); namespace e = example2::inner; e::Print(); using namespace example2; using namespace inner; Print(); }
|
线程
在平常编程过程中,我们所编写的指令都只用了cpu的一个线程,只使用单独线程时当程序中有等待时整个程序都会停下来,使得程序运行效率大大降低,而cpu本身支持多线程运行,也就使得当其中一条指令暂停时程序可以同步进行其他的事情,并且在繁冗的代码中需要大量的计算,多线程可以增加程序处理速度。
基本语法使用:
std::thread 线程名(函数指针);多线程调用
线程名.join();让当前线程等待此线程完工(阻塞当前线程直到另一个线程完工)
std::this_thread::sleep_for(1s);在当前线程中等待1s后再执行后续内容
使用示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #include <iostream> #include <thread>
static bool s_Finished = false;
void Print(int x) { using namespace std::literals::chrono_literals;
std::cout << "当前线程编号为:" << std::this_thread::get_id() << std::endl;
while (!s_Finished) { std::cout << "Hello!"<< x << std::endl; std::this_thread::sleep_for(1s); } }
int main() { std::thread worker(Print,x); std::cin.get(); s_Finished = true;
worker.join();
std::cout << "Finished!" << std::endl; std::cout << "当前线程编号为:" << std::this_thread::get_id() << std::endl; }
|
资料参考:
youtube上the cherno的cpp系列