C++类和对象(中)——拷贝构造 赋值运算符重载

拷贝构造

概念

拷贝构造函数:只有单个形参,该形参是对本类类型对象的引用(一般常用const修饰),在用已存
在的类类型对象创建新对象时由编译器自动调用。

特性 

1. 拷贝构造函数是构造函数的一个重载形式。
2. 拷贝构造函数的参数只有一个且必须是类类型对象的引用,使用传值方式编译器直接报错,
因为会引发无穷递归调用。

class Date
{
public:
    Date(int year = 2023, int month = 9, int day = 7)
    {
        _year = year;
        _month = month;
        _day = day;
    }
    void printf()
    {
        cout << _year << "年" << _month << "月" << _day << "日" << endl;
    }

    //   Date(Date d);          //错误写法,编译报错,会引起无穷递归
    Date(const Date& d)  //正确写法
    {
        _year = d._year;
        _month = d._month;
        _day = d._day;
    }
private:
    int _year;
    int _month;
    int _day;
};
int main()
{
    Date d1;
    Date d2(d1);
    //Date d2 = d1;
    d1.printf();
    d2.printf();
    return 0;
}

 因为在传值传递的时候会调用拷贝构造,调用拷贝构造时又要传值传递,所以会造成无穷递归。

3. 若未显式定义,编译器会生成默认的拷贝构造函数。 默认的拷贝构造函数对象按内存存储按
字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝。
注意:在编译器生成的默认拷贝构造函数中,内置类型是按照字节方式直接拷贝的,而自定
义类型是调用其拷贝构造函数完成拷贝的。

4. 编译器生成的默认拷贝构造函数已经可以完成字节序的值拷贝了,还需要自己显式实现吗?
像日期类这样的类就不需要,但是看看下面的类。 

typedef int DataType;
class Stack
{
public:
    Stack(size_t capacity = 10)
    {
        _array = (DataType*)malloc(capacity * sizeof(DataType));
        if (nullptr == _array)
        {
            perror("malloc申请空间失败");
            return;
        }
            _size = 0;
        _capacity = capacity;
    }
    void Push(const DataType& data)
    {
        // CheckCapacity();
        _array[_size] = data;
        _size++;
    }
    ~Stack()
    {
        if (_array)
        {
            free(_array);
            _array = nullptr;
            _capacity = 0;
            _size = 0;
        }
    }
private:
    DataType* _array;
    size_t _size;
    size_t _capacity;
};
int main()
{
    Stack s1;
    s1.Push(1);
    s1.Push(2);
    s1.Push(3);
    s1.Push(4);
    Stack s2(s1);
    return 0;

 

可以看见程序崩溃了,为什么会造成这种结果呢?如下图:

1. s1对象调用构造函数创建,在构造函数中,默认申请了10个元素的空间

2.s2对象使用s1拷贝构造,这里我们没有定义拷贝构造函数,所以编译器会使用默认的拷贝构造函数,默认拷贝构造函数是按照值拷贝的,因此s1原封不动的拷贝到s2中,s1和s2就会指向同一块空间。

3.指向同一块空间会出现两个问题:(1)插入删除数据会互相影响;(2)析构两次,程序崩溃。

什么时候需要实现拷贝构造呢?

类中如果没有涉及资源申请时,拷贝构造函数是否写都可以;一旦涉及到资源申请
时,则拷贝构造函数是一定要写的,否则就是浅拷贝。如果自己实现了析构函数释放空间,就需要实现拷贝构造。

 5. 拷贝构造函数典型调用场景:

使用已存在对象创建新对象
函数参数类型为类类型对象
函数返回值类型为类类型对象

赋值运算符重载

运算符重载

C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其
返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。
函数名字为:关键字operator后面接需要重载的运算符符号。
函数原型:返回值类型 operator操作符(参数列表)

注意:
1.不能通过连接其他符号来创建新的操作符:比如operator@。
2.重载操作符必须有一个类类型参数。
3.用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不 能改变其含义。
4.作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐
藏的this。
5.   .* :: sizeof ?: . 注意以上5个运算符不能重载。

#include<iostream>
using namespace std;

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}

	// d1 == d2  -》  d1.operator==(d2)
	bool operator==(const Date& d)
	{
		return _year == d._year
			&& _month == d._month
			&& _day == d._day;
	}
	// d1 < d2
	bool operator<(const Date& d)
	{
			if (_year < d._year)
			{
				return true;
			}
			else if (_year == d._year && _month < d._month)
			{
				return true;
			}
			else if (_year == d._year && _month == d._month && _day < d._day)
			{
				return true;
			}
			else
			{
				return false;
			}

		/*return _year < d._year
			|| (_year == d._year && _month < d._month)
			|| (_year == d._year && _month == d._month && _day < d._day);*/
	}

	// d1 <= d2
	bool operator<=(const Date& d)
	{
		return *this < d || *this == d;
	}

	// d1 > d2
	bool operator>(const Date& d)
	{
		return !(*this <= d);
	}
	//d1 >= d2
	bool operator>=(const Date& d)
	{
		return !(*this < d);
	}
	//d1 != d2
	bool operator!=(const Date& d)
	{
		return !(*this == d);
	}
private:
	int _year;
	int _month;
	int _day;
};

		int main()
		{
			Date d1(2023, 9, 9);
			Date d2(d1);
			return 0;
		}

赋值运算符重载

1.赋值运算符重载格式

参数类型:const T&,传递引用可以提高传参效率。
返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值。

检测是否自己给自己赋值,例如d1=d1;
返回*this :要复合连续赋值的含义 。

class Date
{
public :
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
Date (const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
Date& operator=(const Date& d)
{
if(this != &d)                  //这里就是为了防止自己给自己赋值
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
private:
int _year ;
int _month ;
int _day ;
};

2. 赋值运算符只能重载成类的成员函数不能重载成全局函数
3. 用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝。

注意:内置类型成员变量是直接赋值的,而自定义类型成员变量需要调用对应类的赋值运算符重载完成赋值。
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值