C++分配和释放动态数组

  • 分配: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;      //数组大小
};

在这里插入图片描述

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值