C++类的默认成员函数——拷贝构造函数&赋值运算符的重载函数

一. 拷贝构造函数

1. 拷贝构造函数的简单介绍

        在创建对象时使用同类对象来进行初始化,这时用到的构造函数就是拷贝构造函数。拷贝构造函数是一种特殊的构造函数。

2. 拷贝构造函数的特点

(1)拷贝构造函数其实是一个构造函数的重载;

(2)拷贝构造函数的参数必须要用引用传参,使用传值方式会引发无穷递归调用;

(3)若是没有显示定义拷贝构造函数,系统会默认缺省。缺省的拷贝构造函数会依次拷贝类成员进行初始化

3. 传值方式为什么会引发无穷的递归调用?

        简单来说,给函数传参时,形参是实参的一份临时拷贝。若是采用传值的方式,形成形参的时候,要调用拷贝构造函数,然后调用拷贝构造函数又要传参,然后又要调拷贝构造函数......这样就会引发无穷的递归调用。所以调用拷贝构造函数时,一定要引用传参。

4. 拷贝构造函数的简单实现

#include <iostream>
#include <stdlib.h>
using namespace std;
                                                                                                                                                      
class Date
{
    public:
        Date(int year=1900, int month=1, int day=1)
        {
            _year = year;
            _month = month;
            _day = day;
        }
        Date(const Date& d)//拷贝构造函数
        {
            this->_year = d._year;
            this->_month = d._month;
            this->_day = d._day;
        }
        ~Date()
        {}
        void Display()
        {
            cout<<this->_year<<"-"<<_month<<"-"<<_day<<endl;
        }
    private:
        int _year;
        int _month;
        int _day;
};
int main()
{
    Date d1(1998, 5, 27);
    Date d2(d1);//调用拷贝构造函数    
    d1.Display();
    d2.Display();
    return 0;
}

        运行结果为:


二. 赋值运算符的重载

1. 赋值运算符的重载的简单介绍

        赋值运算符的重载是对一个已存在的对象进行拷贝赋值。所有的运算符都可以进行重载,但是只有赋值运算符的重载是默认的成员函数。

2. 拷贝构造函数的简单实现

#include <iostream>
using namespace std;

class Date
{
    public:
        Date(int year=1990, int month=1, int day=1)//构造函数
        {
            _year = year;
            _month = month;
            _day = day;
        }

        ~Date()//析构函数
        {}
        
        Date(const Date& d)//拷贝构造函数
        {
            this->_year = d._year;
            this->_month = d._month;
            this->_day = d._day;
        }

        void Display()
        {
            cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
        }
        ////(1)赋值运算符重载
        ////因为是对一个已存在对象进行赋值,出作用域该对象还在,所以用引用返回
        //Date& operator=(const Date& d1, const Date& d2);
        Date& operator=(const Date& d)
        {//赋值时d1=d3, d1即this,d3即传入的d
            if(this != &d)
            {
                this->_year = d._year;
                this->_month = d._month;
                this->_day = d._day;
            }
            return *this;
        }
int main()
{
    Date d1(1998, 5, 2);
    Date d2(1998, 5, 1);
    d1.Display();
    d2.Display();
    d1 = d2;//调用赋值运算符的重载
    //operator=(d1, d2);
    d1.Display();
    d2.Display();
    return 0;
}

        运行结果为:


三. 拷贝构造函数和赋值运算符的重载函数的区别

        拷贝构造函数是用来对象进行初始化的,它是在创建一个新对象时使用已存在的对象对它进行初始化。

        赋值运算符的重载是用一个已存在的对象给另一个已存在的对象拷贝赋值。









猜你喜欢

转载自blog.csdn.net/lycorisradiata__/article/details/80956701