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

回答編集履歴

2

修正

2020/05/06 14:16

投稿

tiitoi
tiitoi

スコア21960

answer CHANGED
@@ -34,9 +34,10 @@
34
34
  int num;
35
35
  double gas;
36
36
  char *pName;
37
-
37
+
38
38
  public:
39
39
  Car(const char *pN, int n, double g);
40
+ //デストラクタ
40
41
  ~Car();
41
42
  void show();
42
43
  };
@@ -50,27 +51,28 @@
50
51
  strcpy_s(pName, strlen(pN) + 1, pN);
51
52
  num = n;
52
53
  gas = g;
53
- cout << pName << "aa" << endl;
54
+ cout << pName << "を作成しました。" << endl;
54
55
  }
55
56
 
56
57
  Car::~Car()
57
58
  {
58
- cout << pName << "bb" << endl;
59
+ cout << pName << "を破棄します。" << endl;
59
60
  delete[] pName;
60
61
  }
61
62
 
62
63
  void Car::show()
63
64
  {
64
- cout << "n = " << num << " xx" << endl;
65
+ cout << "車のナンバーは" << num << "です。" << endl;
65
- cout << "gas = " << gas << " xx" << endl;
66
+ cout << "ガソリン量は" << gas << "です。" << endl;
66
- cout << "pName = " << pName << " xx" << endl;
67
+ cout << "名前は" << pName << "です。" << endl;
67
68
  }
68
69
 
69
70
  int main()
70
71
  {
71
72
  Car car1("mycar", 1234, 25.5);
72
73
  car1.show();
73
-
74
+
74
75
  return 0;
75
76
  }
77
+
76
78
  ```

1

修正

2020/05/06 14:16

投稿

tiitoi
tiitoi

スコア21960

answer CHANGED
@@ -7,4 +7,70 @@
7
7
  ```diff
8
8
  - Car(char *pN, int n, double g)
9
9
  + Car(const char *pN, int n, double g)
10
+ ```
11
+
12
+ 追記: C++11 だと思っていたのですが、C++03 では、文字列リテラルを char* に変換するのが許可されているので、この点は変更しなくても動きますね。
13
+
14
+ ## 追記
15
+
16
+ Warning の内容はより安全な関数 strcpy_s() を使ってくださいという内容です。
17
+ strcpy との違いはコピーする長さを指定する必要がある点です。
18
+
19
+ ```diff
20
+ - strcpy(pName, pN);
21
+ + strcpy_s(pName, strlen(pN) + 1, pN);
22
+ ```
23
+
24
+ ## 修正後のコード
25
+
26
+ ```cpp
27
+ #include <iostream>
28
+ #include <string>
29
+ using namespace std;
30
+
31
+ class Car
32
+ {
33
+ private:
34
+ int num;
35
+ double gas;
36
+ char *pName;
37
+
38
+ public:
39
+ Car(const char *pN, int n, double g);
40
+ ~Car();
41
+ void show();
42
+ };
43
+
44
+ Car::Car(const char *pN, int n, double g)
45
+ {
46
+ //コンストラクタ内で動的にメモリ確保
47
+ //strlen(pN) pNの中身の文字列のNULLより前の文字数を数える
48
+ pName = new char[strlen(pN) + 1];
49
+ //strcpy(pName, pN) pNameにpNの中身の文字列をコピーする
50
+ strcpy_s(pName, strlen(pN) + 1, pN);
51
+ num = n;
52
+ gas = g;
53
+ cout << pName << "aa" << endl;
54
+ }
55
+
56
+ Car::~Car()
57
+ {
58
+ cout << pName << "bb" << endl;
59
+ delete[] pName;
60
+ }
61
+
62
+ void Car::show()
63
+ {
64
+ cout << "n = " << num << " xx" << endl;
65
+ cout << "gas = " << gas << " xx" << endl;
66
+ cout << "pName = " << pName << " xx" << endl;
67
+ }
68
+
69
+ int main()
70
+ {
71
+ Car car1("mycar", 1234, 25.5);
72
+ car1.show();
73
+
74
+ return 0;
75
+ }
10
76
  ```