C++ 類的棧和堆例項化
阿新 • • 發佈:2019-01-03
#include "stdafx.h" #include <iostream> using namespace std; class Coordnate { public: Coordnate(); ~Coordnate(); int x; int y; void printX() { cout << x << endl; } void printY() { cout << y << endl; } private: }; Coordnate::Coordnate() { } Coordnate::~Coordnate() { } int main() { // 用棧初始化 Coordnate coor; coor.x = 10; coor.y = 20; coor.printX(); coor.printY(); // 用堆初始化 Coordnate *p = new Coordnate(); if (NULL == p) // 初始化失敗的話p為NULL { cout << "Init FAILED" << endl; } p->x = 100; p->y = 200; p->printX(); p->printY(); // 呼叫結束後要刪除,同時要把p重新賦值為NULL delete p; // 如果初始化為陣列,刪除時候為 delete []p; p = NULL; system("pause"); return 0; }
輸出:
程式設計環境:VS2015
這裡展示類例項話的兩種選擇,一種為棧初始化,一種為堆初始化。
在用堆進行例項化的時候要注意記憶體問題。