forked from LearningInfiniTensor/learning-cxx
-
Notifications
You must be signed in to change notification settings - Fork 433
Expand file tree
/
Copy pathmain.cpp
More file actions
77 lines (64 loc) · 2.19 KB
/
main.cpp
File metadata and controls
77 lines (64 loc) · 2.19 KB
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
#include "../exercise.h"
// READ: 派生类 <https://zh.cppreference.com/w/cpp/language/derived_class>
static int i = 0;
struct X {
int x;
X(int x_) : x(x_) {
std::cout << ++i << ". " << "X(" << x << ')' << std::endl;
}
X(X const &other) : x(other.x) {
std::cout << ++i << ". " << "X(X const &) : x(" << x << ')' << std::endl;
}
~X() {
std::cout << ++i << ". " << "~X(" << x << ')' << std::endl;
}
};
struct A {
int a;
A(int a_) : a(a_) {
std::cout << ++i << ". " << "A(" << a << ')' << std::endl;
}
A(A const &other) : a(other.a) {
std::cout << ++i << ". " << "A(A const &) : a(" << a << ')' << std::endl;
}
~A() {
std::cout << ++i << ". " << "~A(" << a << ')' << std::endl;
}
};
struct B : public A {
X x;
B(int b) : A(1), x(b) {
std::cout << ++i << ". " << "B(" << a << ", X(" << x.x << "))" << std::endl;
}
B(B const &other) : A(other.a), x(other.x) {
std::cout << ++i << ". " << "B(B const &) : A(" << a << "), x(X(" << x.x << "))" << std::endl;
}
~B() {
std::cout << ++i << ". " << "~B(" << a << ", X(" << x.x << "))" << std::endl;
}
};
int main(int argc, char **argv) {
X x = X(1);
A a = A(2);
B b = B(3);
// TODO: 补全三个类型的大小
static_assert(sizeof(X) == 4, "There is an int in X");
static_assert(sizeof(A) == 4, "There is an int in A");
static_assert(sizeof(B) == 8, "B is an A with an X");
i = 0;
std::cout << std::endl
<< "-------------------------" << std::endl
<< std::endl;
// 这是不可能的,A 无法提供 B 增加的成员变量的值
// B ba = A(4);
// 这也是不可能的,因为 A 是 B 的一部分,就好像不可以把套娃的外层放进内层里。
A ab = B(5);// 然而这个代码可以编译和运行!
// THINK: 观察打印出的信息,推测把大象放进冰箱分几步?
// THINK: 这样的代码是“安全”的吗?
// NOTICE: 真实场景中不太可能出现这样的代码
i = 0;
std::cout << std::endl
<< "-------------------------" << std::endl
<< std::endl;
return 0;
}