メモリ割り当ての練習をしようとしています。
以下のコードは機能していますが、2 つの質問があります。
割り当て後にメモリを解放するには、どこで delete [ ] を使用する必要がありますか?
show() 関数を使用すると、関数でのこのコードの出力が CDcar になるのはなぜですか?
#include <cstdlib>
#include <new>
#include <iostream>
#include <cstring>
using namespace std;
class automobile {
private:
char (*function)[30];
char *type;
double speed;
public:
automobile ( );
automobile (double , char *);
void speed_up (double);
void speed_down(double);
const char * get_function ( ) const;
void show ( );
};
automobile::automobile ( ) {
speed = 0;
function = new char [1][30];
strcpy(function[1], "CD player with MP3");
type = new char [4];
strcpy(type, "car");
}
automobile::automobile(double spd, char * fn ) {
int sz;
}
void automobile::show ( ) {
cout << "This is a " << type << " and it has the following functions: " << function[1] << ", and its speed is " << speed << " km/h\n";
}
int main ( ) {
automobile car;
car.show ( );
return 0;
}
これは出力です:
This is a car and it has the following functions: CDcar, and its speed is 0 km/h
出力は次のようになるはずだと思いました:
This is a car and it has the following functions: CD player with MP3, and its speed is 0 km/h
お知らせ下さい