Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
Signed-off-by: YdrMaster <[email protected]>
  • Loading branch information
YdrMaster committed Aug 1, 2024
1 parent 56ff1c1 commit 735a24c
Showing 1 changed file with 18 additions and 10 deletions.
28 changes: 18 additions & 10 deletions exercises/15_class_derive/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,43 +2,45 @@

// 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 << "X(" << x << ')' << std::endl;
std::cout << ++i << ". " << "X(" << x << ')' << std::endl;
}
X(X const &other) : x(other.x) {
std::cout << "X(X const &) : x(" << x << ')' << std::endl;
std::cout << ++i << ". " << "X(X const &) : x(" << x << ')' << std::endl;
}
~X() {
std::cout << "~X(" << x << ')' << std::endl;
std::cout << ++i << ". " << "~X(" << x << ')' << std::endl;
}
};
struct A {
int a;

A(int a_) : a(a_) {
std::cout << "A(" << a << ')' << std::endl;
std::cout << ++i << ". " << "A(" << a << ')' << std::endl;
}
A(A const &other) : A(other.a) {
std::cout << "A(A const &) : a(" << a << ')' << std::endl;
A(A const &other) : a(other.a) {
std::cout << ++i << ". " << "A(A const &) : a(" << a << ')' << std::endl;
}
~A() {
std::cout << "~A(" << a << ')' << std::endl;
std::cout << ++i << ". " << "~A(" << a << ')' << std::endl;
}
};
struct B : public A {
X x;

B(int b) : A(1), x(b) {
std::cout << "B(" << a << ", X(" << x.x << "))" << std::endl;
std::cout << ++i << ". " << "B(" << a << ", X(" << x.x << "))" << std::endl;
}
B(B const &other) : A(other.a), x(other.x) {
std::cout << "B(B const &) : A(" << a << "), x(X(" << x.x << "))" << std::endl;
std::cout << ++i << ". " << "B(B const &) : A(" << a << "), x(X(" << x.x << "))" << std::endl;
}
~B() {
std::cout << "~B(" << a << ", X(" << x.x << "))" << std::endl;
std::cout << ++i << ". " << "~B(" << a << ", X(" << x.x << "))" << std::endl;
}
};

Expand All @@ -52,6 +54,7 @@ int main(int argc, char **argv) {
static_assert(sizeof(A) == ?, "There is an int in A");
static_assert(sizeof(B) == ?, "B is an A with an X");

i = 0;
std::cout << std::endl
<< "-------------------------" << std::endl
<< std::endl;
Expand All @@ -65,5 +68,10 @@ int main(int argc, char **argv) {
// THINK: 这样的代码是“安全”的吗?
// NOTICE: 真实场景中不太可能出现这样的代码

i = 0;
std::cout << std::endl
<< "-------------------------" << std::endl
<< std::endl;

return 0;
}

0 comments on commit 735a24c

Please sign in to comment.