C++ 复制构造函数


1. 概念:只有单个形参,而且该形参是对本类类型对象的引用(常用const修饰)。

2. 首先看一个小例子:

.h中:

class Test
{
public:
    Test(int m,float n):a(m),b(n) { }

private:
    int a;
    float b;
};
.cpp中:

int  main()

{

      Test test1(5, 5.5);

      Test test2(1, 1.1);

      cout<<test2.a<<endl;      //很明显,输出1

      cout<<test2.b<<endl;      //很明显,输出1.1

      Test test3(test1);      //或者test3 = test1

      cout<<test3.a<<endl;          //输出5

      cout<<test3.b<<endl;          //输出5.5

      return 0;

}

test3使用了编译器提供的默认复制构造函数,即将类类型对象test1(与test3同类型)的非static成员复制给test3了(如有数组成员,则会逐个数组元素复制。因为数组不支持直接复制,只能遍历复制,所以默认复制构造函数会进行遍历复制数组元素)。。  程序中没有显示提供复制构造函数,所以编译器会合成一个。

2. 显示提供复制构造函数

.h中:

class Test
{
public:
 Test()          //方便定义test2
 {
 }
 Test(int m,float n):a(m),b(n) { }

 Test &test(const Test&);    //显示声明的复制构造函数

public:
 int a;
 float b;
};

.cpp 中

Test &Test::test(const Test& obj)
{
    a = obj.a;      //拷贝的关键.如果注释掉,则当前对象的a和b都是随机值
    b = obj.b;
    return *this;    //返回当前对象
}

int main()

{

    Test test1(2, 5.4);
    Test test2;
    test2.test(test1);    //调用复制构造函数
    cout<<test2.a<<endl;
    cout<<test2.b<<endl;

    return 0;

}

  • 1
  • 2
  • 3
  • 下一页

相关内容