zoukankan      html  css  js  c++  java
  • C++——动态内存分配2-创建对象数组

    //创建对象数组

    #include<iostream>

    using namespace std;

    class Point

    { public:

           Point()

          {   X=Y=0;     cout<<"Default Constructor called."<<endl;     }

           Point(int xx,int yy)

          {   X=xx;     Y=yy;     cout<< "Constructor called."<<endl;     }

           ~Point()

          {   cout<<"Destructor called."<<endl;    }

           int GetX() {return X;}

           int GetY() {return Y;}

              void Move(int x,int y)

                       {  X=x;  Y=y;   }

      private:

           int  X,Y;

    };

     

    int main()

    {

         Point *Ptr=new Point[2];    //创建对象数组

         Ptr[0].Move(5,10);     //通过指针访问数组元素的成员

         Ptr[1].Move(15,20);   //通过指针访问数组元素的成员

         cout<<"Deleting..."<<endl;

         delete[ ] Ptr;               //删除整个对象数组

    }//运行结果:

    Default Constructor called.

    Default Constructor called.

    Deleting...

    Destructor called.

    Destructor called.

    //动态数组类,不需要预先设计好数组的大小

    #include<iostream>

    using namespace std;

    class Point

    { public:

           Point()

          {   X=Y=0;     cout<<"Default Constructor called."<<endl;     }

           Point(int xx,int yy)

          {   X=xx;     Y=yy;     cout<< "Constructor called."<<endl;     }

           ~Point()

          {   cout<<"Destructor called."<<endl;    }

           int GetX() {return X;}

           int GetY() {return Y;}

              void Move(int x,int y)

                       {  X=x;  Y=y;   }

      private:

           int  X,Y;

    };

    class ArrayOfPoints

    {

       public:

         ArrayOfPoints(int n)//根据实际来调整数组大小

         {   numberOfPoints=n;  points=new Point[n];  }

         ~ArrayOfPoints()//

         {   cout<<"Deleting..."<<endl;

             numberOfPoints=0;  delete[] points;     }

         Point& Element(int n)//返回所需要的元素

         {  return points[n];  }

       private:

         Point *points;

         int numberOfPoints;

    };

     

    int main()

    {

             int number;

             cout<<"Please enter the number of points:";

             cin>>number;

         ArrayOfPoints points(number);    //创建对象数组

         points.Element(0).Move(5,10);     //通过指针访问数组元素的成员

         points.Element(1).Move(15,20);   //通过指针访问数组元素的成员

    }

    //运行结果如下:

    Please enter the number of points:2

    Default Constructor called.

    Default Constructor called.

    Deleting...

    Destructor called.

    Destructor called.

  • 相关阅读:
    游戏服务器架构概要
    牛客网_Go语言相关练习_选择题(3)
    Go语言实践_实现一(服务器端)对多(客户端)在线聊天室
    Go语言实践_实现一(客户端)对一(服务器端)聊天室
    牛客网_Go语言相关练习_选择题(2)
    飞鱼48小时游戏创作嘉年华_厦门Pitch Time总结与收获
    牛客网_Go语言相关练习_选择题(1)
    Go语言_iota用法
    游戏服务器概述
    LeetCode_1. Two Sum_Solution
  • 原文地址:https://www.cnblogs.com/lemaden/p/10238025.html
Copyright © 2011-2022 走看看