C++練習 例項化一個座標物件
阿新 • • 發佈:2018-12-15
1.從類名要看出類的功能
2.類的花括號後不要忘了;號
#include <iostream> #include <stdlib.h> using namespace std; class coordinate { public: int x; int y; void printxy() { cout << "(" << x << "," << y << ")" << endl; } }; int main() { cout << "從棧中例項化:" << endl; coordinate coor; //從棧中例項化 coor.x = 5; coor.y = 6; coor.printxy(); cout << "從堆中例項化:" << endl; coordinate *p = new coordinate(); if (NULL == p) { printf("new failure!"); } //如果記憶體分配失敗,列印錯誤資訊 p->x = 4; p->y = 5; p->printxy(); delete p; //用完記得釋放記憶體 p = NULL; system("pause"); }
執行結果: