类的构造和析构基础

#define  _CRT_SECURE_NO_WARNINGS 
#include <iostream>
using namespace std;

class Test
{
public:
    Test()  //无参数 构造函数
    {
        a = 10;  //作用完成对属性的初始化工作
        p = (char *)malloc(100);
        strcpy(p, "aaaaffff");
        cout<<"我是构造函数 被执行了"<<endl;
    }
    void print()
    {
        cout<<p<<endl;
        cout<<a<<endl;
    }
    ~Test() //析构函数
    {
        if (p != NULL)
        {
            free(p);
        }
        cout<<"我是析构函数,被调用了" <<endl;        //被执行了两次,先free那个呢?t2?
    }
protected:
private:
    int a ;
    char *p;
};

//给对象搭建一个舞台,研究对象的行为
void objplay()
{
    //先创建的对象 后释放
    Test t1;
    t1.print();

    printf("分隔符\n");
    Test t2;
    t2.print();
}
void main()
{
    objplay();
    cout<<"hello..."<<endl;
    system("pause");
    return ;
}

7644-106

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值