书法字典:https://www.shufadict.com

拷贝构造函数

什么是拷贝构造函数

拷贝构造函数是一种特殊的构造函数,它的形式如下。

struct Test
{
    Test()
    {

    }
    Test(const Test& other) // 拷贝构造函数
    {
        cout << "Copy constructor" << endl ;
    }
};

什么情况下调用拷贝构造函数

以下几种情况会调用拷贝构造函数。

  • 以一个对象初始化另一个对象
  • 函数以某个对象为参数
  • 函数返回某个对象
  • 初始化序列式容器的元素
struct Test
{
    Test()
    {

    }
    Test(const Test& other)
    {
        cout << "Copy constructor" << endl ;
    }
};

// 函数以类对象为参数,会调用Test的拷贝构造函数
void TestFunc(Test test)
{

}

// 函数返回类的对象,会调用拷贝构造函数
Test TestFunc1()
{
    Test t ;
    return t ;
}

int main ()
{
    Test t ;
    TestFunc(t) ;
    TestFunc1() ;
    Test t1(t) ; // 以一个对象初始化另外一个对象,会调用拷贝构造函数

    // 初始化序列式容器会调用拷贝构造函数
    vector<Test> v(3) ; // 调用一次构造函数及三次拷贝构造函数

    system("pause") ;
    return 0;
}

==

posted on 2010-07-05 21:40  翰墨小生  阅读(1243)  评论(0编辑  收藏  举报

导航

书法字典:https://www.shufadict.com