C++构造、析构的一些理解

wiki: C++类

Effective C++ ——构造/析构/赋值运算符 : 构造/析构/赋值运算符

C++类四个默认函数—构造函数、析构函数、拷贝函数、赋值函数 : 构造函数、析构函数、拷贝函数、赋值函数

C++多个构造函数的问题

概要:

在C++中,每一个类都会有一个或多个构造函数,一个析构函数,一个赋值函数。

 构造函数,包括:无参构造、有参构造、拷贝构造

 本文主要是理解各构造函数的调用问题,即定义一个对象后,调用的是哪个构造函数。

一、知识总结

当我们定义一个空类时,编译器默认会产生4个成员函数:默认无参构造函数、拷贝构造函数、赋值函					数、析构函数。

其中默认的拷贝构造函数是浅拷贝。

如果我们在类中声明了构造函数,那么系统不再提供默认构造函数,此时如果还需要无参构造函数,则需要自己重载构造函数。

调用时,把握一点:

1、定义一个新对象时,一定会有个构造函数被调用。根据定义时所赋的初始值来决定	
该调用哪个构造函数。初始化时不会产生临时对象。

2、有赋值操作,一定会调用赋值函数。根据右值的类型,决定是否要调用带参数的构	
造函数。赋值前会先产生临时对象,然后再调用赋值函数。

二、程序演示

构造函数测试程序

#include "iostream"

using namespace std;

class MyString
{
public:
    MyString()
    {
        m_data = NULL;
        cout<<"无参构造函数"<<endl;
    }

    MyString(const char *str )
    {
        if (str ==NULL)
        {
            m_data = new char[1];
            *m_data = '\0';
        }
        else
        {
            int length;
            length = strlen(str);
            m_data = new char [length+1];

            strcpy(m_data,str);
        }
        cout<<"带参数构造函数 "<<endl;
    }

    MyString(const MyString &other)
    {
        int length;
        length = strlen(other.m_data);
        m_data = new char [length+1];
        strcpy(m_data,other.m_data);

        cout<<"拷贝构造函数"<<endl;

    }

    MyString &operator =( const MyString &other)
    {
        if ( this == &other)
        {
            return *this;
        }
        else
        {
            delete []m_data;

            int length;
            length = strlen(other.m_data);
            m_data = new char[length+1];
            strcpy(m_data,other.m_data);

            cout<<"赋值函数 "<<endl;
            return *this;
        }
    }
    ~MyString()
    {
        if (m_data)
        {
            delete []m_data;
        }
    }

private:
    char *m_data;
};

int main()
{
    cout<<"--------------测试1------------"<<endl;
    MyString str1;

    cout<<"-----------"<<endl;
    str1 = "hello";  //会调用普通构造函数、赋值函数

    cout<<"--------------测试2------------"<<endl;
    MyString str2 = "hello"; //等价于MyString str2("hello"); 


    cout<<"--------------测试3------------"<<endl;
    MyString test("TEST");

    cout<<"-----------"<<endl;
    MyString str3;

    cout<<"---- -----"<<endl;
    str3 = test ;

    cout<<"--------------测试4------------"<<endl;
    MyString str4 = test;


    return 1;
}

三、关于拷贝构造函数
1、定义变量时,若定义时赋的初始值为该类的对象,则调用拷贝构造函数
2、当用按值传递方式传递或返回一个对象时,编译器会自动调用拷贝构造函数!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值