C/C++拷贝构造函数举例

C/C++拷贝构造函数举例


目录
1.拷贝构造函数定义
2.默认拷贝构造函数
3.显式拷贝构造函数
4.参数传递时,调用拷贝构造函数
5.对象作为返回值,调用拷贝构造函数
6.拷贝构造函数,危害(浅拷贝)
7.拷贝构造函数,常用(深拷贝)
8.拷贝构造函数,私有(深拷贝)


正文

1. 拷贝构造函数定义
拷贝构造函数是一种对构造函数的重载。与构造函数有着相同的作用,在创建新对象时,将数值赋值给它们的成员函数。

2.默认拷贝构造函数
若没有将拷贝构造函数显式地定义出来,类具有默认的拷贝构造函数。下记程序里只有带参数arg的构造函数,并未定义拷贝构造函数。

//例1
#include <iostream>
#include <stdio.h>

using namespace std;

class CExample {
   
    private:
        int a;
    public:
        CExample(int arg) {
   
            printf("func: %s\n", __FUNCTION__);
            a = arg;
        }
        void show() {
   
            printf("func:%s, a:%d", __FUNCTION__, a);
        }
};

int main()
{
   
    CExample A(100);
    CExample B = A; // 或者写为 CExample B(A); 结果一样,都是调用默认拷贝构造函数。 
    B.show();
    return 0;
}

输出:
func: CExample
func:show, a:100

3.显式拷贝构造函数
如果类中显式定义拷贝构造函数,则系统会执行定义的显式构造函数。

//例2
#include <iostream>
#include <stdio.h>

using namespace std;

class CExample {
   
    private:
        int a;
    public:
        CExample(int arg) {
   
            printf("func: %s(int arg)\n", __FUNCTION__);
            a = arg;
        }
        CExample(const CExample &C) {
   
            printf("func: %s(const)\n", __FUNCTION__);
            a = C.a;
        }
        void show() {
   
            printf("func:%s, a:%d", __FUNCTION__, a);
        }
};

int main()
{
   
    CExample A(100);
    CExample B = A; // 或者写为, CExample B(A); 
    B.show();
    return 0;
}

输出:
func: CExample(int arg)
func: CExample(const)
func:show, a:100

4.参数传递时,调用拷贝构造函数
对象作为函数参数传递给形参时,调用形参的拷贝构造函数。
将对象test作为实参,传递给g_func()函数时,形参CExample C被赋值为test,相当于执行了CExample C=test;
如果类CExample无显式拷贝构造函数,则执行默认构造函数;
下记类CExample有显示拷贝构造函数CExample(const CExample &C){…},执行该函数。

//例3
#include <iostream>
#include <stdio.h>

using namespace std;

class CExample {
   
    private:
        int a;
    public
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值