1. 程式人生 > >C++類的例項化

C++類的例項化

在c++中定義類,例項物件通常是有兩種方法:

1.從棧中請求空間,例項化物件,建立一個座標的類,程式碼如下:

#include<iostream>

using namespace std;

class Coordinate

{

    public:

         int x;

        int y;

void printfX()

{

   cout<<x<<endl;

}

void printfY()

{

  cout<<y<<endl;

}

} ;

int main()

{

      Coordinate coor;

      coor.x=10;

      coor.y=10;

      coor.printfX();

      coor.printfY();

      return 0;

}

2.從堆中請求空間,例項化物件,建立一個座標的類,程式碼如下:

#include<iostream>

using namespace std;

class Coordinate

{

    public:

         int x;

        int y;

void printfX()

{

   cout<<x<<endl;

}

void printfY()

{

  cout<<y<<endl;

};

int main()

{

  Coordinate  *p=new Coordinate();

 if(NULL==p) 

{

    return 0;

}

p->x=100;

p->y=100;

p->printfX();

p->printfY();

delete p;

p=NULL;

return 0;

}