动态申请内存操作符 new
下面是一个完整的示例,演示了如何分配和释放单个对象和对象数组:
#include<iostream>
using namespace std;
int main() {
//分配和使用单个对象
int * singleInt = new int;//分配内存
*singleInt = 5;//使用分配的内存
cout << "Value of singleInt: " << *singleInt << endl;
delete singleInt;// 释放内存
singleInt = nullptr;//将指针置于nullptr
//分配和使用对象数组
int size = 5;
int* intArray = new int[size];//分配数组内存
for (int i = 0; i < size; ++i) {
intArray[i] = i*2;//使用分配的内存
}
cout << "Values in intArray:";
for(int i = 0; i< size; ++i) {
cout << intArray[i] << " ";
}
cout << endl;
delete[] intArray;//释放数组内存
intArray = nullptr;
return 0;
}
动态创建函数:
#include<iostream>
using namespace std;
class Point {
public:
Point():x(0), y(0) {
cout << "Defalut 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;
}