为什么拷贝构造函数的参数需要加const和引用?

引用:
(值传递)实参到形参的传递过程,形参需要创建新的对象并接收实参的拷贝过程,因此会调用拷贝构造函数。
若拷贝构造函数采用值传递,将会循环调用本身,被编译器所禁止。
const:
为保证程序安全,加上const防止对引用类型参数值的意外修改。

#include <iostream>
using namespace std;

class CExample
{
public:
    CExample(int x) : m_nTest(x)
    {
        cout << "constructor with argument." << endl;
    }
    CExample(const CExample& ex)
    {
        m_nTest = ex.m_nTest;
        cout << "copy constructor." << endl;
    }
    CExample& operator = (const CExample &ex)
    {
        cout << "assignment operator." << endl;
        m_nTest = ex.m_nTest;
        return *this;
    }
    void myTestFunc(CExample ex){

    }
private:
    int m_nTest;
};

int main()
{
    CExample aaa(2);
    CExample bbb(3);
    bbb = aaa;
    CExample ccc = aaa;
    bbb.myTestFunc(aaa);
    system("pause");
    return 0;
}

constructor with argument.
constructor with argument.
assignment operator.
copy constructor.
copy constructor.
请按任意键继续. . .

图片说明

https://blog.csdn.net/qq_26079093/article/details/92971708

全部评论

相关推荐

缒梦&独舞:这家公司是这样的,去年给我实习offer了,不过也是面着玩儿的,他周六还要去做公益志愿活动
点赞 评论 收藏
分享
哥_留个offer先:跟他说,你这个最好用c#,微软就用c#Java不适合这个项目
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务