質問編集履歴
1
見やすく修正しました。誤ったコメント修正。
test
CHANGED
File without changes
|
test
CHANGED
@@ -1,28 +1,74 @@
|
|
1
|
+
```ここに言語を入力
|
2
|
+
|
1
3
|
#include <iostream>
|
2
4
|
|
3
5
|
class testclass {
|
4
6
|
static int count;
|
5
7
|
int id;
|
6
8
|
public:
|
7
|
-
testclass();
|
9
|
+
testclass();
|
8
10
|
int get_id();
|
9
11
|
|
10
12
|
};
|
11
13
|
|
12
14
|
int testclass::count = 0;
|
13
15
|
|
14
|
-
testclass::testclass() {
|
16
|
+
testclass::testclass() {
|
17
|
+
id = ++count;
|
18
|
+
std::cout << "ID " << id << " のオブジェクトを作成します。" << std::endl;
|
19
|
+
|
20
|
+
}
|
21
|
+
int testclass::get_id() {
|
22
|
+
return id;
|
23
|
+
}
|
24
|
+
|
25
|
+
int main() {
|
26
|
+
std::cout << "main()関数開始" << std::endl;
|
27
|
+
testclass obj1, obj2; // 後で同名(obj1)のオブジェクトを作成する
|
28
|
+
std::cout << __LINE__ << ": このオブジェクトのIDは " << obj1.get_id() << " です。" << std::endl;
|
29
|
+
std::cout << __LINE__ << ": このオブジェクトのIDは " << obj2.get_id() << " です。" << std::endl;
|
30
|
+
|
31
|
+
std::cout << "for文に入ります。" << std::endl;
|
32
|
+
for (int i = 0; i < 3; i++) {
|
33
|
+
std::cout << "ループ " << i + 1 << std::endl;
|
34
|
+
testclass obj1; // main()関数で宣言したオブジェクトと同じ名前のオブジェクトを改めて作成
|
35
|
+
std::cout << __LINE__ << ": このオブジェクトのIDは " << obj1.get_id() << " です。" << std::endl;
|
36
|
+
}
|
37
|
+
std::cout << "for文の終わりです。" << std::endl;
|
38
|
+
std::cout << "main()関数終了" << std::endl;
|
39
|
+
return 0;
|
40
|
+
}
|
41
|
+
```
|
42
|
+
このソースは教科書に書いてあった奴です。
|
43
|
+
写真のようになるために、そこにデストラクターを追加したいのですが。
|
44
|
+
|
45
|
+
```ここに言語を入力
|
46
|
+
|
47
|
+
#include <iostream>
|
48
|
+
|
49
|
+
class testclass {
|
50
|
+
static int count;
|
51
|
+
int id;
|
52
|
+
public:
|
53
|
+
testclass();
|
54
|
+
~testclass();デストラクター宣言?
|
55
|
+
int get_id();
|
56
|
+
|
57
|
+
};
|
58
|
+
|
59
|
+
int testclass::count = 0;
|
60
|
+
|
61
|
+
testclass::testclass() {
|
15
62
|
id = ++count;
|
16
63
|
std::cout << "ID " << id << " のオブジェクトを作成します。" << std::endl;
|
17
64
|
|
18
65
|
}
|
19
66
|
|
20
|
-
//変数.get_idが呼び出されたらreturn(初期化)で生存期間が終了。
|
21
67
|
int testclass::get_id() {
|
22
68
|
return id;
|
23
69
|
}
|
24
|
-
//こんな感じで
|
70
|
+
//こんな感じでしょうか?
|
25
|
-
int testclass::
|
71
|
+
int testclass::~testclass() {
|
26
72
|
std::cout << "ID " << id << " のオブジェクトを破棄します。" << std::endl;
|
27
73
|
}
|
28
74
|
|
@@ -41,4 +87,10 @@
|
|
41
87
|
std::cout << "for文の終わりです。" << std::endl;
|
42
88
|
std::cout << "main()関数終了" << std::endl;
|
43
89
|
return 0;
|
90
|
+
}
|
91
|
+
|
92
|
+
```
|
93
|
+
|
94
|
+
また、訂正など必要がありましたらよろしくお願いします。
|
95
|
+
|
44
|
-
|
96
|
+
![実行結果](https://ddjkaamml8q8x.cloudfront.net/questions/2022-05-26/d1d9beaf-3585-42a6-8429-b1cb1841cd36.jpeg)
|