首页 > 编程语言 > 详细

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

时间:2021-07-29 22:18:50      阅读:19      评论:0      收藏:0      [点我收藏+]

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

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

原文:https://www.cnblogs.com/zhjblogs/p/15077034.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!