wly603

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、当用按值传递方式传递或返回一个对象时,编译器会自动调用拷贝构造函数!

(完)

posted on 2012-05-15 14:25  wly603  阅读(5664)  评论(0编辑  收藏  举报

导航