C++ new動態創建對象
View Code代碼就是這樣的簡單。
無參時的創建。
View Code
#include "iostream" #include "string" using namespace std; class Point { public: Point(int x, int y) { cout<<"Default constructor called."<<endl; cout<<x<<" "<<y<<endl; } private: int x, y; }; int main() { Point *ptr1=new Point(1, 2); delete ptr1; }
代碼就是這樣的簡單。
有參時的創建。
View Code
#include "iostream" #include "string" using namespace std; class Point { public: Point():x(0), y(0) { cout<<"Default constructor called."<<endl; cout<<x<<" "<<y<<endl; } private: int x, y; }; int main() { Point *ptr1=new Point[10]; ; delete[] ptr1; }
這個例子是用來展示用new來創建
對象數組的。
posted on 2012-04-19 20:23 More study needed. 閱讀(413) 評論(0) 收藏 舉報

浙公網安備 33010602011771號