动态建立并释放对象

#include "stdafx.h"
#include<iostream>
using namespace std;
class Box
{
    int height;
    int width;
    int length;
public:
    Box();
    Box(int h, int w, int l) :height(h), width(w), length(l) {}
    int volume();
    ~Box();
};


Box::Box()
{
    height = 10;
    length = 10;
    width = 10;
}

int Box::volume()
{
    return (height*width*length);
}

Box::~Box()
{
    cout << "Destructor is called" << endl;
}

int main()
{
    Box *pbox1 = new Box; //定义指向Box堆对象的指针pbox1
    cout << "The volume of box1 is:" << pbox1->volume() << endl;
    delete  pbox1;   //释放pbox1指向的对象空间
    Box *pbox2 = new Box(12, 24, 36);
    cout << "The voiume of box2 is:" << pbox2->volume() << endl;
    delete pbox2;
    system("pause");
    return 0;
}

图像 1

posted @ 2016-05-26 15:22  01Turing  阅读(156)  评论(0编辑  收藏  举报