使用 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)

更新日期:2019 年 7 月 30 日

7K+ 浏览量

开启你的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.