質問するログイン新規登録

質問編集履歴

2

最終的な目標を追記。 Test2.cpp内のvoid Test2::get()内に書かれていたコメントの修正。void Test2::get()内の不要な記載を削除。

2020/03/25 09:58

投稿

mushipan0929
mushipan0929

スコア56

title CHANGED
File without changes
body CHANGED
@@ -5,6 +5,9 @@
5
5
  初期値は共有できますが一旦playerで変更して、別のクラスで共有すると初期値をコピーしてきてしまいます。
6
6
  どうすれば常に別クラスでも共有できるでしょうか?
7
7
 
8
+ 最終的にはTest1::set()内のtest.set_numでnumの数値を[1]にして
9
+ Test2::get()内のget_numで先ほど入れた[1]をTest2内のnumに代入したいです。
10
+
8
11
  ### ソースコード
9
12
  ```C++
10
13
  //Study.cpp
@@ -64,8 +67,7 @@
64
67
 
65
68
  void Test2::get()
66
69
  {
67
- int num = 200;
68
- num = get_num(); //numに200を代入(出来ていない)
70
+ num = get_num(); //numに1を代入(出来ていない)
69
71
  cout << "Test2_num = " << num << endl;
70
72
  }
71
73
 

1

ソースコードを追記しました。

2020/03/25 09:58

投稿

mushipan0929
mushipan0929

スコア56

title CHANGED
File without changes
body CHANGED
@@ -3,4 +3,82 @@
3
3
  現在、コマンドプロンプトで複数の.h/.cppファイルに分けた上で簡単なゲームを作ろうとしていますが
4
4
  player.hで宣言した変数の値をmap.cppで上手く共有できずに困っております。
5
5
  初期値は共有できますが一旦playerで変更して、別のクラスで共有すると初期値をコピーしてきてしまいます。
6
- どうすれば常に別クラスでも共有できるでしょうか?
6
+ どうすれば常に別クラスでも共有できるでしょうか?
7
+
8
+ ### ソースコード
9
+ ```C++
10
+ //Study.cpp
11
+ #include "Test1.h"
12
+ #include "Test2.h"
13
+
14
+ Test1 test1;
15
+ Test2 test2;
16
+
17
+ int main()
18
+ {
19
+ test1.get();
20
+ test1.set();
21
+ test2.get();
22
+
23
+ return 0;
24
+ }
25
+
26
+ //Test1.cpp
27
+ #include "Test1.h"
28
+ #include <iostream>
29
+
30
+ using namespace std;
31
+
32
+ void Test1::get()
33
+ {
34
+ int num = 0;
35
+ num = test2.get_num(); //numに123456789を代入
36
+ cout << "Test1_num = " << num << endl;
37
+ }
38
+
39
+ void Test1::set()
40
+ {
41
+ int num = 1;
42
+ test2.set_num(num); //numに1を代入
43
+ cout << "Test1_num = " << num << endl;
44
+ }
45
+
46
+ //Test1.h
47
+ #pragma once
48
+ #include "Test2.h"
49
+
50
+ class Test1
51
+ {
52
+ public:
53
+ void get();
54
+ void set();
55
+ private:
56
+ Test2 test2;
57
+ };
58
+
59
+ //Test2.cpp
60
+ #include "Test2.h"
61
+ #include <iostream>
62
+
63
+ using namespace std;
64
+
65
+ void Test2::get()
66
+ {
67
+ int num = 200;
68
+ num = get_num(); //numに200を代入(出来ていない)
69
+ cout << "Test2_num = " << num << endl;
70
+ }
71
+
72
+ //Test2.h
73
+ #pragma once
74
+
75
+ class Test2
76
+ {
77
+ public:
78
+ void get();
79
+ int get_num() { return num; }
80
+ void set_num(int _num) { num = _num; }
81
+ private:
82
+ int num = 123456789;
83
+ };
84
+ ```