C++ 对象的动态建立 & 释放
【摘要】
C++ 对象的动态建立 & 释放
概述对象的动态的建立和释放案例对象数组 vs 指针数组对象数组指针数组
概述
通过对象的动态建立和释放, 我们可以提高内存空间的利用率.
...
概述
通过对象的动态建立和释放, 我们可以提高内存空间的利用率.
对象的动态的建立和释放
new 运算符: 动态地分配内存
delete 运算符: 释放内存
当我们用new
运算符动态地分配内存后, 将返回一个指向新对象的指针的值. 我们可以通过这个地址来访问对象. 例如:
int main() {
Time *pt1 = new Time(8, 8, 8);
pt1 -> show_time();
delete pt1; // 释放对象
return 0;
}
输出结果:
8:8:8
当我们不再需要由 new 建立的对象时, 用 delete 运算符释放.
案例
Box 类:
#ifndef PROJECT1_BOX_H
#define PROJECT1_BOX_H
class Box {
public:
// 成员对象
double length;
double width;
double height;
// 成员函数
Box(); // 无参构造
Box(double h, double w, double l); // 有参有参构造
~Box(); // 析构函数
double volume() const; // 常成员函数
};
#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 << "========调用构造函数========\n";
}
double Box::volume() const{
return (height * width * length);
}
Box::~Box() {
cout << "========调用析构函数========\n";
}
main:
#include "Box.h"
#include <iostream>
using namespace std;
int main() {
Box *pt = new Box(16, 12, 10); // 创建指针pt指向Box对象
cout << "长:" << pt->length << "\t";
cout << "宽:" << pt->width << "\t";
cout << "高:" << pt->height << endl;
cout << "体积:" << pt->volume() << endl;
delete pt; // 释放空间
return 0;
}
输出结果:
========调用构造函数========
长:10 宽:12 高:16
体积:1920
========调用析构函数========
对象数组 vs 指针数组
对象数组
固定大小的数组:
const int N = 100;
Time t[N];
动态数组:
const int n = 3; // 定义数组个数
Time *pt = new Time[n]; // 定义指针指向数组
delete []pt; // 释放空间
指针数组
建立占用空间小的指针数组可以帮助我们灵活处理常用空间大的对象集合. (拿时间换空间)
举个栗子:
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;
}
文章来源: iamarookie.blog.csdn.net,作者:我是小白呀,版权归原作者所有,如需转载,请联系作者。
原文链接:iamarookie.blog.csdn.net/article/details/116450231
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
评论(0)