[c++]构造函数和析构函数

构造函数:

1 函数名=类名

2 无返回值(可以没有参数)

3 当用类声明对象时,系统自动调用

4 如果没有构造函数,系统会自动给一个默认的

5 他的功能是给私有成员赋初值

6 可以重载

7 缺省参数的构造函数

8 如果私有成员为数组,则必须用赋值语句(strcpy, for)


析构函数:

1  ~(函数名=类名)

2 无返回值,无参数

3 当程序结束,系统会自动调用析构函数释放对象(碰到 “}” 时进行析构)

4 如果没有构造函数,系统会自动给一个默认的

5 不能重载

6 只要在类里用new分配了空间,一定要在析构函数里用delete释放内存

#include<iostream>
#include<string.h>
using namespace std;
class String_date
{
private:
    char *str;
public:
    String_date(char* s)
    {
        cout<<"constructing:为字符串分配内存";
        cout<<endl;
        str = new char[strlen(s) + 1];
        strcpy(str,s);
    }
    ~String_date(void)
    {
        delete []str;
        cout<<"destructing:释放字符串占用空间";
        cout<<endl;
        
    }
    char *get_info(void)
    {return str;}
};
int main(void)
{
    String_date str1("teacher");
    //String_date str2("qq");
    String_date str2 = str1;//内存泄漏
    cout<<str1.get_info()<<endl;
    return 0;
}

拷贝构造函数

1 是构造函数

2 参数是同类对象的引用

3 直接调用引用对象的私有成

3 用一个已有的对象给同类对象赋初值

Point   A = B 赋值初始化

Point   A(B)  带入初始化

4 形参是类的对象,实参给形参拷贝要调用拷贝构造函数

5 返回值的类型是类当return时会产生一个无名参数此时调用拷贝构造函数

例一:

#include<iostream>
using namespace std;
class A
{
    int x;
public:
    void Print()
    {
        cout<<"A:"<<x<<endl;
    }
    A(int x1)
    {
        x = x1;
        cout<<"structing:"<<x<<endl;
    }//构造
    
    A(const A &A1)
    {
        x = A1.x;
        cout<<"copy structing:"<<x<<endl;
    }//拷贝构造
    
    ~A()
    {
        cout<<"destructing:"<<x<<endl;
    }//析构
};

    void fun1(A A1)//形参为类的对象
    {
        A1.Print();//对应A:1
    }
    A fun2()
    {
        A A2(6);
        return A2;
    }

int main()
{
    A B1(1);
    A B2(2);
    fun1(B1);
    return 0;
}

例二:

#include<iostream>
using namespace std;
class A
{
    int x;
public:
    void Print()
    {
        cout<<"A:"<<x<<endl;
    }
    A(int x1)
    {
        x = x1;
        cout<<"structing:"<<x<<endl;
    }//构造
    
    A(const A &A1)
    {
        x = A1.x;
        cout<<"copy structing:"<<x<<endl;
    }//拷贝构造
    
    ~A()
    {
        cout<<"destructing:"<<x<<endl;
    }//析构
};

    void fun1(A A1)
    {
        A1.Print();
    }
    A fun2()
    {
        A A2(6);//注意这是调用拷贝构造函数时,2已经被改为6所以析构的时候成了6
        return A2;
    }

int main()
{
    A B1(1);
    A B2(2);
    B2 = fun2();//析构一个无名参数
    return 0;
}

例一结果:


例二结果:



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值