动态内存分配的应用:

 

 

 

 1 #include <iostream>
 2 #include <cmath>
 3 using namespace std;
 4 class Point{
 5 public:
 6     Point(int newX=0,int newY=0){
 7         cout << "calling constructor" << endl;
 8         x=newX;
 9         y=newY;
10     }
11     Point(Point &p){
12         x=p.x;
13         y=p.y;
14     }
15     ~Point(){
16         cout << "calling destructor " << endl;
17     }
18     void move(int x,int y){
19         this->x+=x;
20         this->y+=y;
21     }
22     int getX() {
23         return x;
24     }
25     int getY() {
26         return y;
27     }
28 private:
29     int x,y;
30 };
31 class PointsArray{
32 public:
33     PointsArray(int size):size(size){
34      array=new Point[size];  
35     }
36     Point &getElement(int index){
37         if(index>=0&&index<size){
38             return array[index];
39         }
40         else{
41             cout << "invalid index!" << endl;
42         }
43     }
44     ~PointsArray(){
45        delete[] array;
46     }
47 private:
48     Point * array;
49     int size;
50 };
51 int main(){
52     Point *p=new Point(1,2);
53     delete p;
54      int n;
55     cin>>n;
56     PointsArray pa(n);
57     cout<<pa.getElement(0).getX()<<" "<<pa.getElement(0).getY()<<endl;
58     pa.getElement(1).move(1,1);
59     cout<<pa.getElement(1).getX()<<" "<<pa.getElement(1).getY()<<endl;
60     return 0;
61 }

输出结果:

    calling constructor

    calling destructor

动态内存分配:

new 数据类型(初始化形参列表)

int *point = new int;   //没有初值

int *point =new int(); //初值为0

int *a=new int[n];

posted @ 2017-05-20 21:16  稻草人部落  阅读(286)  评论(0编辑  收藏  举报