C++中對象的動態(tài)建立與釋放詳解及其作用介紹
概述
通過對象的動態(tài)建立和釋放, 我們可以提高內(nèi)存空間的利用率.

對象的動態(tài)的建立和釋放
new 運算符: 動態(tài)地分配內(nèi)存
delete 運算符: 釋放內(nèi)存
當(dāng)我們用new運算符動態(tài)地分配內(nèi)存后, 將返回一個指向新對象的指針的值. 我們可以通過這個地址來訪問對象. 例如:
int main() {
Time *pt1 = new Time(8, 8, 8);
pt1 -> show_time();
delete pt1; // 釋放對象
return 0;
}
輸出結(jié)果:
8:8:8
當(dāng)我們不再需要由 new 建立的對象時, 用 delete 運算符釋放.
案例
Box 類:
#ifndef PROJECT1_BOX_H
#define PROJECT1_BOX_H
class Box {
public:
// 成員對象
double length;
double width;
double height;
// 成員函數(shù)
Box(); // 無參構(gòu)造
Box(double h, double w, double l); // 有參有參構(gòu)造
~Box(); // 析構(gòu)函數(shù)
double volume() const; // 常成員函數(shù)
};
#endif //PROJECT1_BOX_H
Box.cpp:
#include <iostream>
#include "Box.h"
using namespace std;
Box::Box() : height(-1), width(-1), length(-1) {}
Box::Box(double h, double w, double l) : height(h), width(w), length(l) {
cout << "========調(diào)用構(gòu)造函數(shù)========\n";
}
double Box::volume() const{
return (height * width * length);
}
Box::~Box() {
cout << "========調(diào)用析構(gòu)函數(shù)========\n";
}
main:
#include "Box.h"
#include <iostream>
using namespace std;
int main() {
Box *pt = new Box(16, 12, 10); // 創(chuàng)建指針pt指向Box對象
cout << "長:" << pt->length << "\t";
cout << "寬:" << pt->width << "\t";
cout << "高:" << pt->height << endl;
cout << "體積:" << pt->volume() << endl;
delete pt; // 釋放空間
return 0;
}
輸出結(jié)果:
========調(diào)用構(gòu)造函數(shù)========
長:10 寬:12 高:16
體積:1920
========調(diào)用析構(gòu)函數(shù)========
對象數(shù)組 vs 指針數(shù)組
對象數(shù)組
固定大小的數(shù)組:
const int N = 100; Time t[N];
動態(tài)數(shù)組:
const int n = 3; // 定義數(shù)組個數(shù) Time *pt = new Time[n]; // 定義指針指向數(shù)組 delete []pt; // 釋放空間

指針數(shù)組
建立占用空間小的指針數(shù)組可以幫助我們靈活處理常用空間大的對象集合. (拿時間換空間)
舉個栗子:
int main() {
const int n = 3;
Time *t[n] = {nullptr};
if (t[0] == nullptr){
t[0] = new Time(8, 8, 8);
}
if (t[1] == nullptr){
t[1] = new Time(6, 6, 6);
}
t[0] -> show_time();
t[1] -> show_time();
return 0;
}

到此這篇關(guān)于C++中對象的動態(tài)建立與釋放詳解及其作用介紹的文章就介紹到這了,更多相關(guān)C++對象的動態(tài)建立與釋放內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c++實現(xiàn)十進制轉(zhuǎn)換成16進制示例
這篇文章主要介紹了c++實現(xiàn)十進制轉(zhuǎn)換成16進制示例,需要的朋友可以參考下2014-05-05
C語言連續(xù)生成多個隨機數(shù)實現(xiàn)可限制范圍
這篇文章主要介紹了C語言連續(xù)生成多個隨機數(shù)實現(xiàn)可限制范圍,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01

