调用析构函数——对象数组

包含析构函数的c++程序

  • 用对象数组的方法输出三个立方体的体积
#include<iostream>
using namespace std;
class box
{public:
  box(int w = 10,int h = 10, int l = 10):height(h),weigh(w),lengh(l){}
  int v();
  private:
  int hight;
  int width;
  int length;
};
int box::volume()
{return(height*length*width);
}
int main()
{box a[3] = {      //定义对象数组
    box(10,12,15),
    box(15,18,20),
    box(16,20,26),
    };
    cout << "v of a[0] is " << a[0].v() << endl;
    cout <<"v of a[1] is " << a[1].v() << endl;
    cout << " v of a[2] is "<< a[2].v() << endl;
    }
  

程序运行结果

v of a[0] is 1800
v of a[1] is 5400
 v of a[2] is 8320

Process returned 0 (0x0)   execution time : 0.016 s
Press any key to continue.
  • 输出学生信息
#include <iostream>

using namespace std;
class student
{public:
    student (int n, string nam, string s)
   {
    num = n;
    name = nam;
    sex = s;
    cout << "constructor called."<< endl;
   }
   ~student() //定义析构函数
   {
       cout << "destructor called." << endl;
   }
   void display()
   {
       cout << "num:" << num << endl;
       cout << "name:" << name << endl;
       cout << "sex:" << sex << endl;
   }
   private:
       int num;
       string name;
       string sex;
};

int main()
{
    student s1(2021524, "张飞", "f");
    s1.display();
    student s2(2021525, "刘备","m");
    s2.display();
    return 0;
}


程序运行结果

constructor called.
num:2021524
name:张飞
sex:f
constructor called.
num:2021525
name:刘备
sex:m
destructor called.
destructor called.

Process returned 0 (0x0)   execution time : 0.012 s
Press any key to continue.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值