-
分配:new 类型名T[数组长度]
数组长度可以是任何整数类型表达式,在运行时计算。 -
释放:delete[] 数组名p
释放指针p所指向的数组。
p必须是用new分配得到的数组首地址。
主程序
#include "pch.h"
#include "Point.h"
int main()
{
Point *ptr = new Point[2];//创建对象数组
ptr[0].move(2, 3); //使用指针访问数组元素的成员
ptr[1].move(3, 4); //使用指针访问数组元素的成员
cout << "Deleting...\n";
delete[] ptr; //删除整个对象数组
return 0;
}
Point.h
#pragma once
#include <iostream>
using namespace std;
class Point
{
public:
Point();
Point(int, int);
~Point();
void move(int, int);
int getX() const { return x; }
int getY() const { return y; }
static void showCount(); //静态函数成员
private:
int x, y;
};
Point.cpp
#include "pch.h"
#include "Point.h"
Point::Point():x(0),y(0)
{
cout << "Default Constructor called.\n";
}
Point::Point(int x, int y) : x(x), y(y)
{
cout << "Constructor called.\n";
}
void Point::move(int newX, int newY)
{
cout << "Moving the point to (" << newX << "," << newY << ").\n";
x = newX;
y = newY;
}
Point::~Point()
{
cout << "Destructor called.\n";
}
将动态数组封装成类
- 更加简洁,便于管理;
- 可以在访问数组元素前检查数组下标是否越界。
Point.cpp文件同上
主程序
#include "pch.h"
#include "Point.h"
int main()
{
int count;
cout << "Please enter the count of the points: ";
cin >> count;
ArrayOfPoints points(count); //创建数组对象
points.element(0).move(5, 0); //访问数组元素的成员
points.element(1).move(15, 20);//访问数组元素的成员
return 0;
}
在Point.h文件中添加PointOfArray动态数组类
#pragma once
#include <iostream>
#include <cassert>
using namespace std;
class Point
{
public:
Point();
Point(int, int);
~Point();
void move(int, int);
int getX() const { return x; }
int getY() const { return y; }
static void showCount(); //静态函数成员
private:
int x, y;
};
class ArrayOfPoints //动态数组类
{
public:
ArrayOfPoints(int size):size(size)
{
points = new Point[size];
}
ArrayOfPoints()
{
cout << "Deleting...\n";
delete[] points;
}
Point& element(int index)
{
assert(index >= 0 && index < size);
return points[index];
}
private:
Point *points; //指向动态数组首地址
int size; //数组大小
};