3 对象的构造和析构

3.1为什么有对象的初始化

        创建对象时,需要做某些初始化的工作,但是类的数据成员不能在声明类的时候初始化,所以编译器提供了一个构造函数来处理对象的初始化。

        构造函数时一种特殊的成员函数,与其他成员函数不同,不需要自己调用,是在建立对象的时候自动执行

3.2 构造函数和析构函数

#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <windows.h>

using namespace std;

class Test{
public:
    //无参构造函数
    Test()
    {
        a = 10;//完成对象的初始化
        p = (char*)malloc(100);
        strcpy(p,"aaaaaaaaaafffffffff");
        cout<<"我是构造函数,被执行了"<<endl;
    }
    void print(){
        cout<<p<<endl;
        cout<<a<<endl;
    }
    ~Test()
    {
        if(p!=NULL){
            free(p);
        }
         cout<<"我是析构函数,被执行了"<<endl;
    }
private:
    int a;
    char *p;
};
//给对象搭建一个舞台,研究对象的行为
void objplay()
{
    //先创建的对象后释放
    Test t1;
    t1.print();
    printf("分隔符\n");
    Test t2;
    t2.print();
}


int main()
{
    objplay();
    cout<<"hello...."<<endl;
    system("pause");
    return 0;
}

构造函数的种类

#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <windows.h>

using namespace std;

class Test1{
public:
    //无参构造函数
    Test1()
    {
        this->a = 0;
        this->b = 0;
        cout<<"无参构造函数"<<endl;
    }

    Test1(int a,int b)
    {
        this->a = a;
        this->b = b;
        cout<<"有参构造函数"<<endl;
    }
    Test1(int a)
    {
        this->a = a;
        this->b = 0;
        cout<<"一个参数的有参构造函数"<<endl;
    }


    Test1(const Test1& obj)
    {
        cout<<"赋值构造函数"<<endl;
    }
    ~Test1()
    {
         cout<<"我是析构函数,被执行了"<<endl;
    }
public:
    void print(){
        cout<<this->a<<endl;
        cout<<this->b<<endl;
        cout<<"普通成员函数"<<endl;
    }

private:
    int a;
    int b;
};

int main()
{
    //括号法
    Test1 t1(1,2);
    t1.print();
    //等号法,这里的等号,C++进行了功能性增强
    Test1 t2 = (3,4);//出错是因为逗号表达式,相当于t2 = 4;所以这里要有一个,一个参数的构造函数
    Test1 t3 = 5;

    Test1 t4 = Test1(1,2);

    t1 = t4; //把t4 copy 给 t1; 赋值操作


    cout<<"hello...."<<endl;
    system("pause");
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值