浅谈拷贝构造函数参数为什么只能是对象引用

1.什么时候会调用拷贝构造函数?

  1. #include <iostream>
    using namespace std;

    class CCTest{
    public:
        int m_nTest2;
        CCTest(int x,int y): m_nTest(x) ,m_nTest2(y)
        {
            cout <<"constructor with argument"<<endl;
        }
        CCTest(const  CCTest &ex)//
        {
            m_nTest = ex.m_nTest;
            m_nTest2 = ex.m_nTest2;
            cout<<"copy constructor"<<endl;
        }
        
        int GetVal()
        {
            return m_nTest;
        }
        
        CCTest& operator = (const CCTest &ex) //赋值运算符重载
        {
            this->m_nTest = ex.m_nTest;
            this->m_nTest2 = ex.m_nTest2;
            cout <<"assignment operator" <<endl;

            return *this;
        }

        void myTestFunc(CCTest ex)//参数为引用的话调用该函数时,拷贝构造函数不会被调用
        {
        }

        CCTest testFunc2()// 如果返回的是对象的引用,则不会调用拷贝构造函数
        {
            cout<<"testFunc2() with a class obj returned!"<<endl;
            CCTest a(1,1);
            CCTest &b =a;
            return b;
        }
        ~CCTest()
        {
           
        }
    private:
        int m_nTest;
    };

    int main()
    {
        CCTest aaa(2,1);
        CCTest bbb(aaa);   //1.用类的对象去初始化另一个对象
        CCTest ccc = aaa;

        ccc.myTestFunc(aaa); //2.形参为类对象,实参初始化形参
        CCTest ddd =  ccc.testFunc2(); //3.函数返回一个类对象时
        return 0;
    }
    运行结果:constructor with argument
    copy constructor
    copy constructor
    copy constructor
    testFunc2() with a class obj returned!
    constructor with argument
    copy constructorr

写了个以类指针为参数的“拷贝构造函数”

    CCTest(CCTest *p)
    {
        m_nTest = p->m_nTest;
        m_nTest2 = p->m_nTest2;

        cout <<"copy constructor with point arg"<<endl;
    }

在mian()函数中   CCTest aaa(2,1);   CCTest *p = &aaa;  CCTest bbb(p) ;//CCTest bbb = p也可以

运行结果:constructor with argument
                  copy constructor with point arg

至于拷贝构造函数的参数为什么规定为类对象的引用,结合众多网友的见解:1.历史原因  2.以指针作为参数只适用于某些简单的情况,如果一个函数的返回值为类指针,此时内存管理很不方便 3.引用使代码的可读性和维护性更好

ps:若有纰漏之处,请大神多多指教,不喜勿碰哟!

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值