C++ || 动态数组

本文介绍了C++中的动态内存分配,包括使用new运算符申请和释放内存,以及如何处理动态数组。文中展示了动态数组的创建、访问和释放,以及通过封装成类来更好地管理和检查边界。此外,文章还涉及了类的构造函数、析构函数、复制构造函数和深拷贝的实现,强调了内存管理的重要性。
摘要由CSDN通过智能技术生成

1.动态内存分配:

动态申请内存操作符 new

        new 类型名T(初始化参数列表)

功能:在程序执行期间,申请用于存放T类型对象的内存空间,并依初值列表赋以初值。

结果值:成功:T类型的指针,指向新分配的内存;失败:抛出异常。

        释放内存操作符delete

        delete 指针p

功能:释放指针p所指向的内存。p必须是new操作的返回值。

#include <iostream>
using namespace std;
class Point {
public:
	Point();
	Point(int x, int y);
	~Point();
	int getX() const; 
	int getY() const; 
	void move(int newX, int newY);
private:
	int x, y;
};

Point::Point() : x(0), y(0) {
    cout<<"Default Constructor called."<<endl;
}
Point::Point(int x, int y) : x(x), y(y) {
    cout<< "Constructor called."<<endl;
}
Point::~Point() { cout<<"Destructor called."<<endl; }
int Point::getX() const { return x; }
int Point::getY() const { return y; }
void Point::move(int newX, int newY) {
    x = newX;
    y = newY;
}


int main(){
	cout << "Step one: " << endl;
	Point *ptr1 = new Point; //调用默认构造函数
	cout<<ptr1->getX()<<endl; //输出GetX
	delete ptr1; //删除对象,自动调用析构函数
	cout << "Step two: " << endl;
	ptr1 = new Point(1,2);
	cout<<ptr1->getX()<<endl; //输出GetX
	delete ptr1;
	return 0;
}

2.

分配和释放动态数组

  • 分配:new 类型名T [ 数组长度 ]

    • 数组长度可以是任何表达式,在运行时计算

  • 释放:delete[] 数组名p

    • 释放指针p所指向的数组。
      p必须是用new分配得到的数组首地址。


#include <iostream>

using namespace std;

class Point {

public:

	Point() : x(0), y(0) {
	cout<<"Default 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); //通过指针访问数组元素的成员
	cout<<ptr[0].getY()<<endl;
	ptr[1].move(15, 20); //通过指针访问数组元素的成员
	cout<<ptr[1].getY()<<endl;   
	cout << "Deleting..." << endl;
	delete[] ptr; //删除整个对象数组
	return 0;
}

3.将动态数组封装成类

  • 更加简洁,便于管理

  • 可以在访问数组元素前检查下标是否越界

#include <iostream>
#include <cassert>
using namespace std;
class Point {
	private:
		int x, y;
	public:
		Point() : x(0), y(0) {
			cout << "Default 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;
		}

};

class ArrayOfPoints { //动态数组类
	private:
		Point *points; //指向动态数组首地址
		int size; //数组大小
	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];
		}
};

int main() {
	int count;
	cout << "Please enter the number of points: ";
	cin >> count;
	ArrayOfPoints points(count); //创建数组对象
	points.element(0).move(5, 0); //访问数组元素的成员
	points.element(1).move(15, 20); //访问数组元素的成员
	return 0;
}

4.动态数组,是相对于静态数组而言。静态数组的长度是编程时程序员预先定义好的,在整个程序运行中,数组大小无法改变。而动态数组则不然,它可以随程序运行的需要而在运行时重新指定大小。

        动态数组的内存空间是从堆(heap)上分配(即动态分配)的。是通过执行new(或malloc等函数)操作,而为其分配存储空间。当程序执行到这些语句时,才为其分配。

        对于动态数组类所申请的内存,在使用完必须由程序员自己释放,否则严重会引起内存泄露。所以内存的申请一定要有借有还,才能再借不难,也要注意,不能多还。

        已知动态数组模板类的定义如下。

请补充完整

        1)构造函数

        2)析构函数

        3)返回空间大小的 capacity()  函数

        4)operator[] 重载

#include <cstring>
#include <iostream>
 
using namespace std;
 
class Point {
    int x, y;
 
   public:
    // constructor
    Point(int _x = 0, int _y = 0);
    // deconstructor
    ~Point();
    // cout <<  overload
    friend ostream& operator<<(ostream& os, const Point& p);
};
 
Point::Point(int _x, int _y) {
    this->x = _x;
    this->y = _y;
    cout << "\nPoint is called!";
}
 
Point::~Point() { cout << "\n~Point is called!"; }
 
ostream& operator<<(ostream& os, const Point& p) {
    cout << "(" << p.x << "," << p.y << ")";
    return os;
}
 
template <typename T>
class DynamicArray {
   private:
    T* array;                 // pointer
    unsigned int mallocSize;  // the length of dynamic array
 
   public:
    // Constructors
    // mallocSize=length, and the new element is content
    DynamicArray(unsigned length, const T& content);
 
    // Destructors
    ~DynamicArray();
 
    // Copy Constructor
    DynamicArray(const DynamicArray<T>& anotherDA);
 
    // return the this->mallocSize
    unsigned int capacity() const;
 
    // for the array[i]=someT.
    T& operator[](unsigned int i);

};
 
template <typename T>
DynamicArray<T>::DynamicArray(unsigned length, const T& content) {
    this->mallocSize = length;
    cout << endl
         << "new T[" << this->mallocSize << "] malloc " << this->mallocSize
         << "*" << sizeof(T) << "=" << this->mallocSize * sizeof(T)
         << " bytes memory in heap";
    this->array = new T[this->mallocSize];
    for (int i = 0; i < length; ++i) {
        this->array[i] = content;
    }
};
 
template <typename T>
DynamicArray<T>::~DynamicArray() {
    cout << endl
         << "delete[] array free " << this->mallocSize << "*" << sizeof(T)
         << "=" << this->mallocSize * sizeof(T) << " bytes memory in heap";
    delete[] array;
};
  
template <typename T>
unsigned int DynamicArray<T>::capacity() const {
    return this->mallocSize;
}
 
template <typename T>
T& DynamicArray<T>::operator[](unsigned int i) {
    return this->array[i];
}
 
int main()
{
    int length,i;
    cin>> length;

    DynamicArray<int> iarray(length,-1);
    DynamicArray<double> darray(length,-2.1);

    cout<<endl<<"capacity:"<<iarray.capacity()<<endl;

    for(i=0;i<length;i++) {
        cout << iarray[i] <<" ";
        iarray[i] = i*1.1;
    }
    cout<<endl;
    for(i=0;i<length;i++) {
        cout << darray[i] <<" ";
        darray[i] = i*1.1;
    }
    cout<<endl;
    for(i=0;i<length;i++) {
        cout << iarray[i] <<" ";
        iarray[i] = i*1.1;
    }
    cout<<endl;
    for(i=0;i<length;i++) {
        cout << darray[i] <<" ";
    }
}

         5)operator[]  const 重载

template <typename T>
class DynamicArray {
private:
T* array; //pointer  ,一个T类型的指针
unsigned int mallocSize; //分配空间的大小。

public:
//Constructors 
// cout<<endl<< "new T["<<this->mallocSize<<"] malloc "<< this->mallocSize << "*"<<sizeof(T)<<"="<<this->mallocSize *sizeof(T)<<" bytes memory in heap";
DynamicArray(unsigned length, const T &content) ; // mallocSize=length; 设置每个元素的初始内容是 content;

// Destructors
// cout<<endl<< "delete[] array free "<< this->mallocSize << "*"<<sizeof(T)<<"="<<this->mallocSize *sizeof(T)<<" bytes memory in heap";
~DynamicArray();

//return the this->mallocSize
unsigned int capacity() const;

// for the array[i]=someT.
T& operator[](unsigned int i) ;

//自己定义个operator[]  const 重载
T& operator[] (unsigned int i) const;

};

template <typename T>
DynamicArray<T>::DynamicArray(unsigned length, const T& content) {
    this->mallocSize = length;
    cout << endl
         << "new T[" << this->mallocSize << "] malloc " << this->mallocSize
         << "*" << sizeof(T) << "=" << this->mallocSize * sizeof(T)
         << " bytes memory in heap";
    this->array = new T[this->mallocSize];
    for (int i = 0; i < length; ++i) {
        this->array[i] = content;
    }
};
 
template <typename T>
DynamicArray<T>::~DynamicArray() {
    cout << endl
         << "delete[] array free " << this->mallocSize << "*" << sizeof(T)
         << "=" << this->mallocSize * sizeof(T) << " bytes memory in heap";
    delete[] array;
};
  
template <typename T>
unsigned int DynamicArray<T>::capacity() const {
    return this->mallocSize;
}
 
template <typename T>
T& DynamicArray<T>::operator[](unsigned int i) {
    return this->array[i];
}

template <typename T>
T& DynamicArray<T>::operator[](unsigned int i) const{
    return this->array[i];
}

        6)实现一个copy构造函数

#include <cstring>
#include <iostream>
 
using namespace std;
 
class Point {
    int x, y;
 
   public:
    // constructor
    Point(int _x = 0, int _y = 0);
    // deconstructor
    ~Point();
    // cout <<  overload
    friend ostream& operator<<(ostream& os, const Point& p);
};
 
Point::Point(int _x, int _y) {
    this->x = _x;
    this->y = _y;
    cout << "\nPoint is called!";
}
 
Point::~Point() { cout << "\n~Point is called!"; }
 
ostream& operator<<(ostream& os, const Point& p) {
    cout << "(" << p.x << "," << p.y << ")";
    return os;
}
 

template <typename T>
class DynamicArray {
private:
T* array; //pointer  ,一个T类型的指针
unsigned int mallocSize; //分配空间的大小。

public:
//Constructors 
// cout<<endl<< "new T["<<this->mallocSize<<"] malloc "<< this->mallocSize << "*"<<sizeof(T)<<"="<<this->mallocSize *sizeof(T)<<" bytes memory in heap";
DynamicArray(unsigned length, const T &content) ; // mallocSize=length; 设置每个元素的初始内容是 content;

//Copy Constructor
// cout<<endl<< "Copy Constructor is called";
DynamicArray(const DynamicArray<T> & anotherDA ) ;

// Destructors
// cout<<endl<< "delete[] array free "<< this->mallocSize << "*"<<sizeof(T)<<"="<<this->mallocSize *sizeof(T)<<" bytes memory in heap";
~DynamicArray();

//return the this->mallocSize
unsigned int capacity() const;

// for the array[i]=someT.
T& operator[](unsigned int i) ;

//自己定义个operator[]  const 重载
};



template <typename T>
DynamicArray<T>::DynamicArray(unsigned length, const T& content) {
    this->mallocSize = length;
    cout << endl
         << "new T[" << this->mallocSize << "] malloc " << this->mallocSize
         << "*" << sizeof(T) << "=" << this->mallocSize * sizeof(T)
         << " bytes memory in heap";
    this->array = new T[this->mallocSize];
    for (int i = 0; i < length; ++i) {
        this->array[i] = content;
    }
};
 
template <typename T>
DynamicArray<T>::~DynamicArray() {
    cout << endl
         << "delete[] array free " << this->mallocSize << "*" << sizeof(T)
         << "=" << this->mallocSize * sizeof(T) << " bytes memory in heap";
    delete[] array;
};
 
template <typename T>
DynamicArray<T>::DynamicArray(const DynamicArray<T>& anotherDA) {
    // this = anotherDA;
    cout << endl << "Copy Constructor is called";
    this->mallocSize = anotherDA.mallocSize;
    this->array = new T[this->mallocSize];
    for (int i = 0; i < this->mallocSize; ++i)
        this->array[i] = anotherDA.array[i];
};
 

template <typename T>
unsigned int DynamicArray<T>::capacity() const {
    return this->mallocSize;
}
 
template <typename T>
T& DynamicArray<T>::operator[](unsigned int i) {
    return this->array[i];
}
 

int main()
{
int length,i;
cin>> length;

DynamicArray<int> iarray(length,-1);

DynamicArray<int> iarray2(iarray);

cout<<endl;
for(i=0;i<length;i++) {
	cout << iarray[i] <<" ";
	iarray[i] = i*1.1;
}
cout<<endl;
for(i=0;i<length;i++) {
	cout << iarray2[i] <<" ";	
}

return 0;
}

        7)实现深赋值,操作符= 的重载

#include <cstring>
#include <iostream>
 
using namespace std;
 
class Point {
    int x, y;
 
   public:
    // constructor
    Point(int _x = 0, int _y = 0);
    // deconstructor
    ~Point();
    // cout <<  overload
    friend ostream& operator<<(ostream& os, const Point& p);
};
 
Point::Point(int _x, int _y) {
    this->x = _x;
    this->y = _y;
    cout << "\nPoint is called!";
}
 
Point::~Point() { cout << "\n~Point is called!"; }
 
ostream& operator<<(ostream& os, const Point& p) {
    cout << "(" << p.x << "," << p.y << ")";
    return os;
}
 
template <typename T>
class DynamicArray {
private:
T* array; //pointer  ,一个T类型的指针
unsigned int mallocSize; //分配空间的大小。

public:
//Constructors 
// cout<<endl<< "new T["<<this->mallocSize<<"] malloc "<< this->mallocSize << "*"<<sizeof(T)<<"="<<this->mallocSize *sizeof(T)<<" bytes memory in heap";
DynamicArray(unsigned length, const T &content) ; // mallocSize=length; 设置每个元素的初始内容是 content;

//Copy Constructor
// cout<<endl<< "Copy Constructor is called";
DynamicArray(const DynamicArray<T> & anotherDA ) ;

// Destructors
// cout<<endl<< "delete[] array free "<< this->mallocSize << "*"<<sizeof(T)<<"="<<this->mallocSize *sizeof(T)<<" bytes memory in heap";
~DynamicArray();

//return the this->mallocSize
unsigned int capacity() const;

// for the array[i]=someT.
T& operator[](unsigned int i) ;

//自己定义个operator[]  const 重载

//自己定义个 operator = 重载

// 函数内要输出  cout<<endl<<"operator = is called";

DynamicArray<T> & operator= (const DynamicArray<T> & anotherDA ) ;

};


template <typename T>
DynamicArray<T>::DynamicArray(unsigned length, const T& content) {
    this->mallocSize = length;
    cout << endl
         << "new T[" << this->mallocSize << "] malloc " << this->mallocSize
         << "*" << sizeof(T) << "=" << this->mallocSize * sizeof(T)
         << " bytes memory in heap";
    this->array = new T[this->mallocSize];
    for (int i = 0; i < length; ++i) {
        this->array[i] = content;
    }
};
 
template <typename T>
DynamicArray<T>::~DynamicArray() {
    cout << endl
         << "delete[] array free " << this->mallocSize << "*" << sizeof(T)
         << "=" << this->mallocSize * sizeof(T) << " bytes memory in heap";
    delete[] array;
};
 
template <typename T>
DynamicArray<T>::DynamicArray(const DynamicArray<T>& anotherDA) {
    // this = anotherDA;
    cout << endl << "Copy Constructor is called";
    this->mallocSize = anotherDA.mallocSize;
    this->array = new T[this->mallocSize];
    for (int i = 0; i < this->mallocSize; ++i)
        this->array[i] = anotherDA.array[i];
};
 
template <typename T>
DynamicArray<T>& DynamicArray<T>::operator=(const DynamicArray<T>& anotherDA) {
    cout << endl << "operator = is called";
    if (this == &anotherDA) return *this;
    if (this->array) delete[] this->array;
    this->mallocSize = anotherDA.mallocSize;
    this->array = new T[this->mallocSize];
    for (int i = 0; i < this->mallocSize; ++i)
        this->array[i] = anotherDA.array[i];
    return *this;
}
 
template <typename T>
unsigned int DynamicArray<T>::capacity() const {
    return this->mallocSize;
}
 
template <typename T>
T& DynamicArray<T>::operator[](unsigned int i) {
    return this->array[i];
}
 
int main()
{
int length,i;
cin>> length;

DynamicArray<int> iarray(length,-1);

DynamicArray<int> iarray2(iarray),iarray3(iarray2);

cout<<endl;
for(i=0;i<length;i++) {
	cout << iarray3[i] <<" ";
	iarray[i] = i*1.1;	
}
iarray3=iarray2=iarray;
cout<<endl;
for(i=0;i<length;i++) {
	cout << iarray3[i] <<" ";	
}

return 0;
}

        8)实现深赋值,操作符= 的重载

                Point类动态数组应用

                实现一个Point类,实现

                class Point {
                     int x,y;
                     public:
                            //构造函数,输出 cout<<"\nPoint is called!";  并完成私有成员的初始化

                            //析构函数,输出    cout<<"\n~Point is called!";

                           //友元输出函数,输出   "("<<p.x<<","<<p.y<<")";
                  };

#include <cstring>
#include <iostream>
 
using namespace std;
 
class Point {
    int x, y;
 
   public:
    // constructor
    Point(int _x = 0, int _y = 0);
    // deconstructor
    ~Point();
    // cout <<  overload
    friend ostream& operator<<(ostream& os, const Point& p);
};
 
Point::Point(int _x, int _y) {
    this->x = _x;
    this->y = _y;
    cout << "\nPoint is called!";
}
 
Point::~Point() { cout << "\n~Point is called!"; }
 
ostream& operator<<(ostream& os, const Point& p) {
    cout << "(" << p.x << "," << p.y << ")";
    return os;
}
 
template <typename T>
class DynamicArray {
   private:
    T* array;                 // pointer
    unsigned int mallocSize;  // the length of dynamic array

    
	public:
	//Constructors 
	// cout<<endl<< "new T["<<this->mallocSize<<"] malloc "<< this->mallocSize << "*"<<sizeof(T)<<"="<<this->mallocSize *sizeof(T)<<" bytes memory in heap";
	DynamicArray(unsigned length, const T &content) ; // mallocSize=length; 设置每个元素的初始内容是 content;
	
	//Copy Constructor
	// cout<<endl<< "Copy Constructor is called";
	DynamicArray(const DynamicArray<T> & anotherDA ) ;
	
	// Destructors
	// cout<<endl<< "delete[] array free "<< this->mallocSize << "*"<<sizeof(T)<<"="<<this->mallocSize *sizeof(T)<<" bytes memory in heap";
	~DynamicArray();
	
	//return the this->mallocSize
	unsigned int capacity() const;
	
	// for the array[i]=someT.
	T& operator[](unsigned int i) ;   
	 //自己定义个operator[]  const 重载
	
	//自己定义个 operator = 重载
	
	// 函数内要输出  cout<<endl<<"operator = is called";
    DynamicArray<T>& operator=(const DynamicArray<T>& anotherDA);
};
 
template <typename T>
DynamicArray<T>::DynamicArray(unsigned length, const T& content) {
    this->mallocSize = length;
    cout << endl
         << "new T[" << this->mallocSize << "] malloc " << this->mallocSize
         << "*" << sizeof(T) << "=" << this->mallocSize * sizeof(T)
         << " bytes memory in heap";
    this->array = new T[this->mallocSize];
    for (int i = 0; i < length; ++i) {
        this->array[i] = content;
    }
};
 
template <typename T>
DynamicArray<T>::~DynamicArray() {
    cout << endl
         << "delete[] array free " << this->mallocSize << "*" << sizeof(T)
         << "=" << this->mallocSize * sizeof(T) << " bytes memory in heap";
    delete[] array;
};
 
template <typename T>
DynamicArray<T>::DynamicArray(const DynamicArray<T>& anotherDA) {
    // this = anotherDA;
    cout << endl << "Copy Constructor is called";
    this->mallocSize = anotherDA.mallocSize;
    this->array = new T[this->mallocSize];
    for (int i = 0; i < this->mallocSize; ++i)
        this->array[i] = anotherDA.array[i];
};
 
template <typename T>
DynamicArray<T>& DynamicArray<T>::operator=(const DynamicArray<T>& anotherDA) {
    cout << endl << "operator = is called";
    if (this == &anotherDA) return *this;
    if (this->array) delete[] this->array;
    this->mallocSize = anotherDA.mallocSize;
    this->array = new T[this->mallocSize];
    for (int i = 0; i < this->mallocSize; ++i)
        this->array[i] = anotherDA.array[i];
    return *this;
}
 
template <typename T>
unsigned int DynamicArray<T>::capacity() const {
    return this->mallocSize;
}
 
template <typename T>
T& DynamicArray<T>::operator[](unsigned int i) {
    return this->array[i];
}
 
int main()
{
int length,i;
cin>> length;

DynamicArray<Point> iarray(length,Point(3));

DynamicArray<Point> iarray2(iarray),iarray3(iarray2);

cout<<endl;
for(i=0;i<length;i++) {
	cout << iarray3[i] <<" ";
	iarray[i] = Point(i,i+1);	
}
iarray3=iarray2=iarray;
cout<<endl;
for(i=0;i<length;i++) {
	cout << iarray3[i] <<" ";	
}

return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小嘤嘤怪学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值