动态申请内存操作符 new
new 类型名T(初始化参数列表)
功能:在程序执行期间,申请用于存放T类型对象的内存空间,并依初值列表赋以初值。
结果值:成功:T类型的指针,指向新分配的内存;失败:抛出异常(如果内存空间满足不了申请的内存空间就会抛出异常)
释放内存操作符delete
delete 指针P
功能:释放指针P所指向的内存。p必须是new操作的返回值
#include<iostream>
using namespace std;
class Point
{
public:
Point() :x(0), y(0) {
cout << "Defaule Constructor called." << endl;
}
Point(int x, int y) :x(x), y(y) {
cout << "Constructor called." << endl;
}
~Point()
{
cout << "Destructor called." << endl;
}
int getX()const { return x; }
int getY()const { return y; }
void move(int newX, int newY) {
x = newX;
y = newY;
}
private:
int x, y;
};
int main() {
cout << "Step one:" << endl;
Point *ptr1 = new Point;//调用默认构造函数
delete ptr1;//删除对象,自动调用析构函数
cout << "Step two:" << endl;
ptr1 = new Point(1, 2);
delete ptr1;
return 0;
}
分配和释放动态数组
分配:new 类型名T[数组长度]
数组长度可以是任何整数表达式,在运行时计算
释放:delete[]数组名p
释放指针p所指向的数组。p必须是用new分配得到的数组首地址
#include<iostream>
using namespace std;
class Point
{
public:
Point() :x(0), y(0) {
cout << "Defaule Constructor called." << endl;
}
Point(int x, int y) :x(x), y(y) {
cout << "Constructor called." << endl;
}
~Point()
{
cout << "Destructor called." << endl;
}
int getX()const { return x; }
int getY()const { return y; }
void move(int newX, int newY) {
x = newX;
y = newY;
}
private:
int x, y;
};
int main() {
Point* ptr = new Point[2];//创建数组对象
ptr[0].move(5, 10);
ptr[1].move(15, 20);//通过指针访问数组元素的成员
cout << "Deleting..." << endl;
delete[] ptr;//删除整个对象数组
return 0;
}
动态创建多维数组
new 类型名T[第一维度][第二维度]...;
如果内存申请成功,new运算返回一个指向新分配内存首地址的指针。
例如:char(*fp)[3];
fp = new char[2][3];
#include<iostream>
using namespace std;
int main() {
int(*cp)[9][8] = new int[7][9][8];
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 9; j++)
{
for (int k = 0; k < 8; k++)
{
*(*(*(cp + i) + j) + k) = (i * 100 + j * 10 + k);
}
}
}
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 9; j++)
{
for (int k = 0; k < 8; k++)
{
cout << cp[i][j][k] << "";
}
cout << endl;
}
cout << endl;
}
delete[]cp;
return 0;
}
将动态数组封装成类
1.更加简洁,便于管理。 2.可以在访问数组元素前检查下标是否越界
#include<iostream>
#include<cassert>
using namespace std;
class Point
{
public:
Point() :x(0), y(0) {
cout << "Defaule Constructor called." << endl;
}
Point(int x, int y) :x(x), y(y) {
cout << "Constructor called." << endl;
}
~Point()
{
cout << "Destructor called." << endl;
}
int getX()const { return x; }
int getY()const { return y; }
void move(int newX, int newY) {
x = newX;
y = newY;
}
private:
int x, y;
};
class ArrayOfPoints{
public:
ArrayOfPoints(int size) :size(size) {
points = new Point[size];
}
~ArrayOfPoints() {
cout << "Deleting..." << endl;
delete[] points;
}
Point& element(int index) {
assert(index >= 0 && index < size);
return points[index];
}
private:
Point* points;
int size;
};
int main() {
int count;
cout << "Please enter the count of points:";
cin >> count;
ArrayOfPoints points(count);
points.element(0).move(5, 0);
points.element(1).move(15, 20);
return 0;
}