-
Notifications
You must be signed in to change notification settings - Fork 0
/
03-module.ixx
144 lines (109 loc) · 1.99 KB
/
03-module.ixx
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include <stdexcept>
#include <iostream>
#include <cassert>
#include <vector>
#include <map>
#include <complex>
export module _03_module;
using namespace std;
export class Vector {
public:
Vector(int s);
double& operator[](int i);
int size();
private:
double* elem;
int sz;
};
Vector::Vector(int s){
if (s < 0) {
throw length_error{ "Vector consturctor: negative size" };
}
elem = new double[s];
sz = s;
}
double& Vector::operator[](int i) {
if (i < 0 || i >= sz) {
throw out_of_range("Vector::operator[]");
}
return elem[i];
}
int Vector::size() {
return sz;
}
export int size(Vector& v) { return v.size(); }
// 3.4 命名空间
namespace My_code {
class complex{};
}
My_code::complex c;
// 3.5 错误处理
// a. 异常
void f(Vector& v) noexcept{
try {
v[v.size()] = 7; // exp!
}
catch (out_of_range& err) {
cout << err.what() << '\n';
}
}
// b. 不变式
// c. 错误处理替代
// d. 合约
void fn(const char* p) {
assert(p != nullptr);
}
// e. 静态断言
static_assert(sizeof(int) >= 4, "int are too small");
// 3.6 函数参数&返回值
// a. 参数传递 => 默认“传值”
void test(vector<int> v, vector<int>& rv) {
v[1] = 99;
rv[2] = 66;
}
void print(int value, int base = 10);
// b. 返回值
int& bad() {
int x = 0;
return x; //error! 返回局部变量的引用
}
class Matrix {};
Matrix operator+(const Matrix& x, const Matrix& y) {
Matrix res;
//...
return res;
}
Matrix m1, m2;
Matrix m3 = m1 + m2; // copy
Matrix* add(const Matrix& x, const Matrix& y) { // 1990s 风格 :)
Matrix* p = new Matrix;
//...
return p;
}
void _f() {
Matrix m1, m2;
Matrix* pm = add(m1, m2);
delete pm;
}
auto mul(int i, double d) { return i * d; }
// 3.6.3 结构化绑定
struct Entry {
string name;
int value;
};
Entry read_entry(istream& is) {
string s;
int i;
is >> s >> i;
return { s,i };
}
auto e = read_entry(cin);
void __fn() {
auto [n, v] = read_entry(cin);
map<string, int> m;
for (const auto [key, value] : m) {
cout << key << value << "\n";
}
std::complex<double> z = { 1,2 };
auto e = z + 2.;
}