ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 基本数据类型的动态分配 <details> <summary>main.cpp</summary> ``` #include <iostream> using namespace std; int main() { //基本数据类型 int *i1=new int; int *i2=new int(); int *i3=new int(100); float *i4=new float(1.11f); cout << "i1 = " <<*i1 << endl; cout << "i2 = " <<*i2 << endl; cout << "i3 = " <<*i3 << endl; cout << "i4 = " <<*i4 << endl; //数组 int *iArr = new int[3]; for (size_t i = 0; i < 3; i++) { iArr[i]=i; cout << i << " : " << iArr[i] << endl; } // 释放内存 delete i1; delete i2; delete i3; delete i4; delete []iArr; return 0 ; } ``` </details> <br/> ## 内存分配时的出错处理 <details> <summary>main.cpp</summary> ``` #include <iostream> using namespace std; int main() { //判断指针是否为NULL double *arr1 = new double[100000]; if (!arr1) { cout << "内存分配出错!" << endl; return 1; } delete[] arr1; // try catch try { double *arr2 = new double[100000]; delete[] arr2; } catch (const std::exception &e) { std::cerr << "内存分配出错!" << endl; return 1; } double *arr3 = new (nothrow) double[100000]; if (!arr3) { cout << "内存分配出错!" << endl; return 1; } delete[] arr3; cout << "内存分配成功!" << endl; return 0; } ``` </details> <br/> ## 用new产生类的实例 <details> <summary>main.cpp</summary> ``` #include <iostream> using namespace std; class A { public: int x; void setX(int x) { this->x = x; } int getX() { return this->x; } }; int main() { A *a = new A(); if (!a) { cout << "内存分配出错!" << endl; return 1; } a->setX(123); cout << a->getX() << endl; delete a; return 0; } ``` </details> <br/>