C++之拷贝构造函数(内容来自菜鸟教程)

拷贝构造函数是一种特殊的构造函数,它在创建对象时,是使用同一类中之前创建的对象来初始化新创建的对象。拷贝构造函数通常用于:

  • 通过使用另一个同类型的对象来初始化新创建的对象。

  • 复制对象把它作为参数传递给函数。

  • 复制对象,并从函数返回这个对象。

如果在类中没有定义拷贝构造函数,编译器会自行定义一个。如果类带有指针变量,并有动态内存分配,则它必须有一个拷贝构造函数。

上代码:

*   Copyright (C) 2020 Sangfor Ltd. All rights reserved.
*   
*   文件名称:10.cpp
*   创 建 者:陈    丁
*   创建日期:2020年05月05日
*   描    述:
*
================================================================*/


#include<iostream>
using namespace std;
class Line{
    public:
        int getLength(void);
        Line(int len);
        Line(const Line&obj);
        ~Line();
    private:
        int *ptr;
};
Line::Line(int len){
    cout<<"diao yong gou zao func():"<<endl;
    ptr=new int;
    *ptr=len;
}
Line::Line(const Line&obj){
    cout<<"调用拷贝构造函数并且为指zhen ptr分配内存"<<endl;
    ptr=new int ;
    *ptr=*obj.ptr;
}
Line::~Line(void){
    cout<<"release memory"<<endl;
    delete ptr;
}
int Line::getLength(void){
    return *ptr;
}
void display(Line obj){
    cout<<"value of line"<<obj.getLength()<<endl;
}
int main()
{
    Line line(10);
    display(line);
    return 0;
}

通过使用已有的同类型的对象来初始化新创建的对象

上代码:

#include <iostream>
 
using namespace std;
 
class Line
{
   public:
      int getLength( void );
      Line( int len );             // 简单的构造函数
      Line( const Line &obj);      // 拷贝构造函数
      ~Line();                     // 析构函数
 
   private:
      int *ptr;
};
 
// 成员函数定义,包括构造函数
Line::Line(int len)
{
    cout << "调用构造函数" << endl;
    // 为指针分配内存
    ptr = new int;
    *ptr = len;
}
 
Line::Line(const Line &obj)
{
    cout << "调用拷贝构造函数并为指针 ptr 分配内存" << endl;
    ptr = new int;
    *ptr = *obj.ptr; // 拷贝值
}
 
Line::~Line(void)
{
    cout << "释放内存" << endl;
    delete ptr;
}
int Line::getLength( void )
{
    return *ptr;
}
 
void display(Line obj)
{
   cout << "line 大小 : " << obj.getLength() <<endl;
}
 
// 程序的主函数
int main( )
{
   Line line1(10);
 
   Line line2 = line1; // 这里也调用了拷贝构造函数
 
   display(line1);
   display(line2);
 
   return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值