C++ 基础

public protected private

public在任何地方都能访问。proteted和private不能被实例访问,但可以被友元函数访问。

public继承,基类权限不变;派生类成员函数可访问基类public和protected,不能访问private

protected继承,基类的public成员在派生类中的权限变成了protected;派生类成员函数可访问基类public和protected,不能访问private。

private继承,基类的所有成员在派生类中的权限变成了private;派生类成员函数可访问基类public、protected,不能访问基类private成员。

多线程

使用std::thread

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <thread>

void print_sum(int a, int b) {
std::cout << "The sum is: " << a + b << std::endl;
}

int main() {
std::thread t(print_sum, 3, 5);
t.join();
return 0;
}

当出现线程之间资源竞争时,需要用mutex锁

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
#include <iostream>
#include <mutex>
#include <thread>

std::mutex mtx;

void print_block(int n, char c) {
{
std::unique_lock<std::mutex> locker(mtx);
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << std::endl;
}
}

int main() {
std::thread t1(print_block, 50, '*');
std::thread t2(print_block, 50, '$');

t1.join();
t2.join();

return 0;
}