使用 new 还是不使用 new 实例化 C++ 对象有什么区别?
在 C++ 中,我们可以使用或不使用 new 关键字实例化类对象。如果未使用 new 关键字,则它就像普通的对象。将存储在堆栈部分。当作用域结束时将被销毁。但当我们想要动态地为项目分配空间时,我们可以创建该类的指针,并使用 new 运算符实例化。
在 C++ 中,new 用于动态分配内存。
示例
#include <iostream>
using namespace std;
class Point {
int x, y, z;
public:
Point(int x, int y, int z) {
this->x = x;
this->y = y;
this->z = z;
}
void display() {
cout << "(" << x << ", " << y << ", " << z << ")" << endl;
}
};
int main() {
Point p1(10, 15, 20);
p1.display();
Point *ptr;
ptr = new Point(50, 60, 70);
ptr->display();
}输出
(10, 15, 20) (50, 60, 70)
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP