C++初阶:类和对象(三)——拷贝构造函数和运算符重载

目录

一、拷贝构造函数

1.概念

2.特性

二、赋值运算符重载

1.运算符重载

2.赋值运算符重载

(1)注意的点:

(2)赋值运算符不允许被重载为全局函数,只能重载为类的成员函数

(3)用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝


一、拷贝构造函数

1.概念

拷贝构造函数是特殊的成员函数,能够使用已经存在的同类对象为新对象进行初始化。

2.特性

  • 拷贝构造函数是构造函数的一种重载形式
  • 拷贝构造函数的参数有且只有一个,且该参数必须为已经存在的同类对象的引用(一般常常使用const进行修饰,因为我们只是希望进行拷贝,而不是对原对象进行修改),如果采用传值调用的形式,编译器会直接报错,因为这将会引发无穷递归(调用拷贝构造函数进行值传递时需要创建一个形参,而形参又要调用拷贝构造函数来获取实参,程序会崩溃)
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
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)   // 正确写法
	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);
	return 0;
}
  • 若无显示创建拷贝构造函数,编译器将生成一个默认拷贝构造函数。默认的拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝
class Time
{
public:
	Time()
	{
		_hour = 1;
		_minute = 1;
		_second = 1;
	}
	Time(const Time& t)
	{
		_hour = t._hour;
		_minute = t._minute;
		_second = t._second;
		cout << "Time::Time(const Time& t)" << endl;
	}
private:
	int _hour;
	int _minute;
	int _second;
};
class Date
{
private:
	// 基本类型(内置类型)
	int _year = 2024;
	int _month = 3;
	int _day = 9;
	// 自定义类型
	Time _t;
};
int main()
{
	Date d1;
	// 用已经存在的d1拷贝构造d2,此处会调用Date类的拷贝构造函数
   // 但Date类并没有显式定义拷贝构造函数,则编译器会给Date类生成一个默认的拷贝构造函数
	Date d2(d1);
	return 0;
}

        注意:在编译器生成的默认拷贝构造函数中,内置类型是按照字节方式直接拷贝的,而自定 义类型是调用其拷贝构造函数完成拷贝的。

        看下面一串代码,试运行一下并观察结果。

	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;
	}
}

        好家伙,程序崩溃了~看下面的图(主要是因为两个对象的_array指向了同一块内存空间,当s2释放_array指向的空间时,s1的_array指向的内存空间与s2销毁前_array指向的空间一致,导致了该空间重复多次释放

        由此,我们看到了浅拷贝的弊端之一——在申请资源(开辟空间)时,不同对象内部的指针会指向同一块空间,导致析构时出现异常。类中如果没有涉及资源申请时,拷贝构造函数是否写都可以;一旦涉及到资源申请时,则拷贝构造函数是一定要写的,否则就是浅拷贝。

        对于上面的代码,可以添加一个拷贝构造函数,这样编译器就不会自动生成了,想要修改s2里面_array的值可以再写一个别的函数来修改。下面的这个函数就属于深拷贝的拷贝构造函数,因为这是我按照所需自行设定的拷贝构造函数。

Stack(const Stack& data)
{
	_capacity = data._capacity;
	_size = data._size;
	_array = nullptr;
}

        为了提高程序效率,一般对象传参时,尽量使用引用类型,返回时根据实际场景,能用引用 尽量使用引用。

二、赋值运算符重载

1.运算符重载

        C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。

         函数名字为:关键字operator后面接需要重载的运算符符号。

         函数原型:返回值类型 operator操作符(参数列表)

bool operator==(const Date& d1, const Date& d2)
 {
     return d1._year == d2._year
     && d1._month == d2._month
     && d1._day == d2._day;
 }

注意:

  • 不能通过连接其他符号来创建新的操作符:比如operator@(在C/C++中@不是操作符)
  • 重载操作符必须有一个类类型参数
  • 用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不能改变其含义(可以理解为在内置类型之间(不包含自定义类型)或者是作用于内置类型本身的操作符含义不容改变,即该运算符无法重载)
  • 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this指针
  • .* (使用指针的,不常见,知道即可) ::(域限定操作符)  sizeof  ?:(三目运算符)  .(成员访问) 注意以上5个运算符不能重载。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
//运算符重载
class Date
{
public:
	Date(int year=2024,int month=3,int day=10)
	{
		_year = year;
		_month = month;
		_day = day;
	}
private:
	int _year;
	int _month;
	int _day;
};
bool operator==(const Date&d1,const Date&d2)
{
	return d1._year == d2._year
		&& d1._month == d2._month
		&& d1._day == d2._day;
}
int main()
{
	Date d1(2024, 1, 6);
	Date d2;
    //这里需要注意运算符的优先级
	cout << (d1 == d2) << endl;
	return 0;
}

        此时,你会发现编译器报错了,为什么呢?因为Date类对象内部的成员变量是私有的,无法通过外部全局函数来访问。

        那有什么解决办法吗?有的,法一是使用下一节我们将会讲到的友元函数,法二是可以将这个全局函数重载成为一个成员函数封装到类中去。代码如下:

//法一:友元函数
class Date
{
public:
	Date(int year=2024,int month=3,int day=10)
	{
		_year = year;
		_month = month;
		_day = day;
	}
    //添加一个friend,你是我的朋友了,所以我内部的成员允许你的访问
	friend bool operator==(const Date& d1, const Date& d2);
private:
	int _year;
	int _month;
	int _day;
};
//法二:==运算符作成员函数重载
class Date
{
public:
	Date(int year=2024,int month=3,int day=10)
	{
		_year = year;
		_month = month;
		_day = day;
	}
    //其实还是有两个操作数的,函数的第一个参数是默认的this指针
    //bool operator==(Date* this,const Date& d)
	bool operator==(const Date& d)
	{
		return _year == d._year
			&& _month == d._month
			&& _day == d._day;
	}
private:
	int _year;
	int _month;
	int _day;
};

2.赋值运算符重载

(1)注意的点

  • 针对内置类型允许连续赋值的特点,自定义类型的赋值运算符也应该要允许连续赋值
  • 连续赋值有一个前提,就是类型一致性
  • 参数类型应该是类的类型,const Class&(引用类型为最佳,能够优化性能和速度)
  • 返回值类型应该为类的引用,提高运行效率,支持连续赋值
  • 返回的应该是*this(被赋值对象的引用)
class Date
{
public:
	Date(int year=2024,int month=3,int day=10)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void show()
	{
		cout << _year << "年" << _month << "月" << _day << "日" << endl;
	}
	Date& operator=(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
		return *this;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d1(2024, 1, 6);
	Date d2;
	d1 = d2;
	d1.show();
	return 0;
}

(2)赋值运算符不允许被重载为全局函数,只能重载为类的成员函数

Date& operator=(Date& left, const Date& right)
{
	if (&left != &right)
	{
		left._year = right._year;
		left._month = right._month;
		left._day = right._day;
	}
	return left;
}

        原因:赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户再在类外自己实现 一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值运算符重载只能是类的成员函数。

(3)用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
//运算符重载
class Date
{
public:
	Date(int year = 2024, int month = 3, int day = 10)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void show()
	{
		cout << _year << "年" << _month << "月" << _day << "日" << endl;
	}
	//Date& operator=(const Date& d)
	//{
	//	_year = d._year;
	//	_month = d._month;
	//	_day = d._day;
	//	return *this;
	//}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1(2024, 1, 6);
	Date d2;
	d1 = d2;
	d1.show();
	return 0;
}

        注意:内置类型成员变量是直接赋值的,而自定义类型成员变量需要调用对应类的赋值运算符重载完成赋值(请读者自行实现,但是请记住一点自定义类型的赋值和拷贝构造,归根结底还是对内置类型的赋值和拷贝)。 

        编译是成功的,诶,同拷贝构造函数一样,当只是涉及到值拷贝的时候,编译器自动生成的赋值运算符重载是足够的,但是当涉及到申请资源的时候,就会和拷贝构造函数一样,程序会崩溃啦~

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;
	s2 = s1;
	return 0;
}

3.前置++与后置++重载

int getMonthDay[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
class Date
{
public:
	Date(int year = 2024, int month = 3, int day = 10)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void show()
	{
		cout << _year << "年" << _month << "月" << _day << "日" << endl;
	}
	bool operator==(const Date& d)
	{
		return _year == d._year
			&& _month == d._month
			&& _day == d._day;
	}
    //由于前置++是得到的直接是+1后的结果,那么直接返回使用前置++对象的引用即可
	Date& operator++()
	{
		if (_day < getMonthDay[_month])
		{
			_day++;
		}
		else
		{
			_month++;
			_day = 1;
		}
		return *this;
	}
    //由于后置++是得到的是+1前的结果,先创建一个临时对象来接收原对象数值,然后对++对象进行自增,最后返回临时对象的值(不能返回引用,否则这将会造成野引用)
	Date operator++(int i)
	{
		Date temp = *this;
        //使用前置自增,因为这里的实现逻辑与前置++一致了
		++*this;
		return temp;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d1(2024, 1, 1);
	Date d2(2024, 3, 1);
    //创建一个新的变量d3来接受后置++的返回值,验证成功性
	Date d3=d1++;
	d1.show();
	d3.show();
	++d2;
	d2.show();
	return 0;
}

        观察上述代码,为了区分前置++与后置++,C++研发者规定了需要在后置++的参数列表中添加一个int型形参,在隐式使用时不需要传入参数,但是如果是显示调用时,需要手动补齐参数(运算符重载不允许使用缺省参数),下面的截图是前置++,你可以在()随便写一个值使其成为后置++。


        在下一节中,我将会通过日期类的实现来进一步地体现已有的类成员函数。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值