我正在尝试为内存分配做一些练习。
我有以下代码正在运行,但有两个问题。
分配后我必须在哪里使用 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
请指教