C++类复制构造函数

来源:互联网 发布:java初始化spring容器 编辑:程序博客网 时间:2024/06/06 02:47

C++标准中提缺省构造函数、拷贝构造函数、拷贝赋值操作符和析构函数是特殊成员函数。

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

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

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

X::X(X& x)X::X(const X& x)X::X(X& x, int a = 0, int b = 1…)

 什么时候会调用拷贝构造函数?以下三种情况出现时,会调用一个类的拷贝构造函数:
    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 b();                     // 不能用这种方式声明CA的对象b    PairInteger c(10, 10);                                  PairInteger d(c);                      // 情况1) 用一个已经实例化了的该类对象,去实例化该类的另外一个对象    int anInt = passObjectByValue(c);      // 情况2) 用该类的对象传值的方式作为一个函数的参数    PairInteger e = returnObject(11, 11);  // 情况3) 一个函数返回值为该类的一个对象(在dev c++下没有调用拷贝构造函数,有待考察)    return 0;}


FROM:  http://www.cnblogs.com/ggjucheng/archive/2011/12/14/2287473.html


0 0
原创粉丝点击