forked from mcpp-community/d2mcpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10-delegating-constructors-1.cpp
More file actions
92 lines (73 loc) · 2.25 KB
/
10-delegating-constructors-1.cpp
File metadata and controls
92 lines (73 loc) · 2.25 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// d2mcpp: https://github.com/mcpp-community/d2mcpp
// license: Apache-2.0
// file: dslings/cpp11/10-delegating-constructors-1.cpp
//
// Exercise/练习: cpp11 | 10 - delegating constructors | 委托构造函数注意事项
//
// Tips/提示: 根据编译器的输出, 修复编译器报错, 了解委托构造函数的注意事项
//
// Docs/文档:
// - https://en.cppreference.com/w/cpp/language/initializer_list.html#Delegating_constructor
// - https://github.com/mcpp-community/d2mcpp/blob/main/book/src/cpp11/10-delegating-constructors.md
//
// Auto-Checker/自动检测命令:
//
// d2x checker delegating-constructors
//
#include <d2x/cpp/common.hpp>
#include <iostream>
#include <string>
struct Object { // 不要修改这个类的代码
static int construction_counter;
std::string name;
Object() {
construction_counter++;
}
Object(std::string name_) : name { name_ } {
construction_counter++;
}
};
class Account {
std::string id;
std::string name;
std::string coin;
Object obj;
public:
Account(std::string id_)
: Account(id_, "momo"), coin { "100元" }
{
}
Account(std::string id_, std::string name_) {
Account(id_, name_, 0);
}
Account(std::string id_, std::string name_, int coin_) {
id = id_;
name = name_;
coin = std::to_string(coin_) + "元";
obj = Object(name_);
}
std::string get_id() const {
return id;
}
std::string get_object_name() const {
return obj.name;
}
std::string to_string() const {
return "Account { id: " + id + ", name: " + name + ", coin: " + coin
+ ", Object { name: " + obj.name
+ ", construction_counter: " + std::to_string(Object::construction_counter) + " } }";
}
};
int Object::construction_counter { 0 };
int main() { // 不要修改main函数中的代码
Account a1 { "1111", "hello" };
std::cout << a1.to_string() << std::endl;
d2x_assert(a1.get_id() == "1111");
Object::construction_counter = 0;
Account a2 { "2222", "d2learn", 100 };
std::cout << a2.to_string() << std::endl;
d2x_assert(a2.get_object_name() == "d2learn");
d2x_assert_eq(Object::construction_counter, 1);
D2X_WAIT
return 0;
}