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