C++拷贝构造函数和赋值构造函数

typedef struct Test
{
    char a;
    int b;
    short c;
    double d;
    std::string str;
    Test()
    {
        a = 0;
        b = 0;
        c = 0;
    }
    Test(const Test& aoTest)
    {
        printf("test copy\n");
        str = aoTest.str;
    }
    Test& operator = (const Test& aoTest)
    {
        printf("=test=\n");
        if (this != &aoTest)
        {
             a = aoTest.a;
             b = aoTest.b;
             d = aoTest.d;
            str = aoTest.str;
        }

        return *this;
    }
}Test;

1、对于函数是值传递类型调用的是拷贝构造函数,传引用类型不会调用拷贝构造函数
2、如果是把对象赋值给新创建的对象调用的是拷贝构造函数。
需要注意的是如果结构中含有自定义类型的需要自己提高拷贝构造函数和赋值构造函数,否则会导致浅拷贝的问题。

Test test1;
Test test2;
Test test3 = test1;//调用拷贝构造函数
test2 = test3;//调用的是赋值构造函数


版权声明:本文为gbbfum原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。