私はメモリ割り当てのためのいくつかの練習をしようとしています。割り当て後にどこでメモリを解放する必要がありますか?
以下のコードは動作していますが、2つの質問があります。
割り当て後にメモリを解放するには、delete []を使用する必要がありますか。
show()関数を使用しているときに、このコードの出力が関数であるのはなぜですか?
#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
私は、出力はこのことshoud考えた:
This is a car and it has the following functions: CD player with MP3, and its speed is 0 km/h
〜自動車デストラクタ内部
なぜタイトルと質問が異なるのですか? – UmNyobe
なぜ 'std :: string'、ahmadを使わないのですか? – jrok
@UmNyobe質問はどこでメモリを解放しなければならないのですか?タイルは同じです。私は出力について別の質問があります。 – Jack