C++“拷贝构造函数”和“等号重载”有什么区别?

CTypeA(const CTypeB& b)
CTypeA& operator=(const CTypeB& b)
一直没弄懂这两个有什么区别。

只知道,重载了=号,下面复制的时候就不调用拷贝构造函数了。

CTypeA a1;
CTypeB b1;
a1 = b1;

那什么时候会有区别?

class CTypeB
{
public:
    int b;
};

class CTypeA
{
public:
    int a;

    CTypeA(){}

    CTypeA(const CTypeB& b)
        :a(b.b)
    {
    }

    CTypeA& operator=(const CTypeB& b)
    {
        a = b.b;
        return *this;
    }

    operator CTypeB()
    {
        CTypeB b;
        b.b = a;
        return *this;
    }
};

答:

正所谓其名,拷贝构造函数是在构造对象的时候用,而等号重载则在在赋值的时候用 CTypeA a; CTypeA b(a); //在构造b CTypeA b = a; //在构造b b = a; //在赋值

http://blog.csdn.net/swgsunhj/article/details/37871249

posted @ 2021-07-29 20:47  北极星!  阅读(651)  评论(0编辑  收藏  举报