C++类复制构造函数

1.构造函数不能有返回类型,也不能由virtual, const, static 和 volatile来修饰。但可以由inline来修饰,事实上隐式构造函数就是用inline来修饰的。inline表示编译时展开,通常速度块;virtual表示运行时绑定,通常意味着灵活。

2.类中存在虚函数或者有虚基类的情况下需要显式声明构造函数。拷贝构造函数也是如此。

3.构造函数是一种特殊函数,而拷贝构造函数是一种特殊的构造函数。类X的构造函数的第一个参数必须为X&,或者const X&;除了第一个参数外,构造函数要么不存在其他参数,如果存在其他参数,其他参数必须有默认值。一个类可以有多个拷贝构造函数。

 

 

什么时候会调用拷贝构造函数?以下三种情况出现时,会调用一个类的拷贝构造函数:
    1) 用一个已经实例化了的该类对象,去实例化该类的另外一个对象;
    2) 用该类的对象传值的方式作为一个函数的参数;
    3) 一个函数返回值为该类的一个对象。

 

示例代码:

 

#include <iostream>
using namespace std;

class PairInteger
{
public:
    int m_a;
    int m_b;
public:
    inline PairInteger()
    {   
        m_a = 1;
        m_b = 2;
    }   

    inline PairInteger(int a, int b)
    {   
        m_a = a;
        m_b = b;
    }   

    inline PairInteger(const PairInteger& other)
    {   
        m_a = other.m_a;
        m_b = other.m_b;
        cout << "copy constructor is called." << endl;
    }   

    inline PairInteger(PairInteger& other)
    {   
        m_a = other.m_a;
        m_b = other.m_b;
        cout << "copy constructor is called." << endl;
    }
    
    void printInfo()
    {   
        cout << "a = " << m_a << ", b = " << m_b << endl;
    }   
};

int passObjectByValue(PairInteger pairInteger)
{
    return pairInteger.m_a + pairInteger.m_b;
}

PairInteger returnObject(int a, int b)
{
    PairInteger ca(a, b);
    return ca;
}

int main(void)
{   
    PairInteger a;
    //PairInteger x();                     // 不能用这种方式声明CA的对象x
    PairInteger c(10, 10);                              
    PairInteger d(c);                      // 情况1) 用一个已经实例化了的该类对象,去实例化该类的另外一个对象
    int anInt = passObjectByValue(c);      // 情况2) 用该类的对象传值的方式作为一个函数的参数
    PairInteger e = returnObject(11, 11);  // 情况3) 一个函数返回值为该类的一个对象(在dev c++下没有调用拷贝构造函数,有待考察)
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值