码迷,mamicode.com
首页 > 其他好文 > 详细

动态内存分配的应用:

时间:2017-05-20 21:48:18      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:动态内存分配   内存分配   math   color   class   call   turn   pac   结果   

 

 

 

 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

动态内存分配的应用:

标签:动态内存分配   内存分配   math   color   class   call   turn   pac   结果   

原文地址:http://www.cnblogs.com/kblin/p/6883206.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!