我对 C++ 很陌生,我想澄清一些关于使用运算符“new ...”和运算符“delete ...”的内存管理的要点。
我将发布我的一些代码,如果它们是错误的,请您纠正我的评论。
我也在处理虚函数和接口,这通过阅读代码很清楚,我还问你我是否以正确的方式接近它们。
那么我有一个更直接的问题,我应该什么时候使用“new[] ...”或“delete[] ...”,我应该如何正确使用它们?
PS:下面代码的输出是:
car built
motorcycle built
car has 4 wheels
motorcycle has 2 wheels
car destroyed
motorcycle destroyed
那是 main.cpp 源:
#include <iostream>
using namespace std;
class vehicle
{
public:
virtual
~vehicle()
{
}
virtual void
wheelNum() = 0;
};
class car : public vehicle
{
public:
car()
{
cout << "car built" << endl;
}
~car()
{
cout << "car destroyed" << endl;
}
void
wheelNum()
{
cout << "car has 4 wheels" << endl;
}
};
class motorcycle : public vehicle
{
public:
motorcycle()
{
cout << "motorcycle built" << endl;
}
~motorcycle()
{
cout << "motorcycle destroyed" << endl;
}
void
wheelNum()
{
cout << "motorcycle has 2 wheels" << endl;
}
};
int
main()
{
// motorVehicle[2] is allocated in the STACK and has room for 2 pointers to vehicle class object
// when I call "new ...", I allocate room for an object of vehicle class in the HEAP and I obtain its pointer, which is stored in the STACK
vehicle* motorVehicle[2] = { new (car), new (motorcycle) };
for (int i = 0; i < 2; i++)
{
// for every pointer to a vehicle in the array, I access the method wheelNum() of the pointed object
motorVehicle[i] -> wheelNum();
}
for (int i = 0; i < 2; i++)
{
// given that I allocated vehicles in the HEAP, I have to eliminate them before terminating the program
// nevertheless pointers "motorVehicle[i]" are allocated in the STACK and therefore I don't need to delete them
delete (motorVehicle[i]);
}
return 0;
}
谢谢大家。