首页 > 代码库 > 动态内存分配的应用:
动态内存分配的应用:
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
动态内存分配的应用:
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。