C++—— 类与对象(二)“构造函数”,“析构函数”,“拷贝函数”,“赋值运算符重载”,

1. 类的6个默认成员函数

一个类中什么成员都没有,称为空类。空类在编译时,编译器会自动生成6个默认成员函数。默认成员函数:用户没有显现形式,编译器会默认生成的成员函数。
在这里插入图片描述

2. 构造函数

2.1 构造函数的概念

构造函数是特殊的成员函数,名字与类相同创建类、类型对象时由编译器自动调用,以保证每一个数据成员都有一个合适的初始值,并且在对象的整个声明周期内只调用一次。

2.2 构造函数的特性

  1. 无返回值。
  2. 函数名与对象名向同。
  3. 对象实例化时编译器自动调用对应的构造函数。
  4. 构造函数可以重载。
class Date
{
public:
	//无参构造
	Date()
	{
		
	}
	//带参构造
	Date(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
public:
	void Print()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}

private:

	int _year;
	int _month;
	int _day;

};

int main()
{
	Date d2;
	Date d1(2024, 2, 2);
	d1.Print();
	d2.Print();

	return 0;
}
  1. 如果类中没有显示定义构造函数,C++编译器就会自动生成一个无参的默认构造函数,但是有定义构造函数编译器就不生成。

  2. 关于编译器生成的默认构造函数,对内置类不做处理,自定义类型回去调用他的默认构造函数。内置类/基本类型: int/char/double/指针/语言自身定义的类型。
    自定义类型 : struct/class。

//自定义类型
class A
	{
	public:
		A()
		{
			cout << "A()" << endl;
			_a = 0;
		}
	private:
		int _a;
	};
	
	class Date
	{
	public:
		void Print()
		{
			cout << _year << "-" << _month << "-" << _day << endl;
		}
	
	private:
		
		int _year ;
		int _month ;
		int _day;
	
		A _aa;
	};

int main()
{
	Date d1;
	
	return 0;
}
  1. 若是类中没有定有构造函数,可以在声明内置类中给缺省值。(缺省值是给初始化列表用的)
class Date
{
public:
	void Print()
	{
		
		cout << this->_year << "/" << this->_month << "/" << this->_day << endl;
	}
	//在声明处给缺省值
	int _year =1;   
	int _month =1;
	int _day = 1;
};

  1. 无参的构造函数、全缺省的构造函数和编译器默认生成的构造函数都称为默认构造函数,默认构造函数就只能有一个。(推荐使用全缺省构造函数)

3. 析构函数

3.1 析构函数的定义

析构函数是特殊的成员函数,析构函数与构造函数的功能相反,析构函数并不时是完成对对象的销毁。对象在销毁时会自动调用析构函数,完成对象中的资源的清理工作。

3.2 析构函数的特性

  1. 析构函数的函数名是在类名前面加上字符~。
  2. 无参数无返回值。
  3. 在对象生命周期结束时,编译器会自动调用析构函数。(满足后定义的先析构)
  4. 一个类只能有一个析构函数。若没有显示定义,系统会自动生成默认的析构函数。注意:析构函数不能重载。默认析构函数跟构造函数类似,内置类不做处理 ,自定义类型的成员自动调用他的析构函数。
  5. 如果类中没有申请资源时,析构函数可以不写,直接使用编译器生成的默认析构函数,比如 Date类;有资源申请时,一定要写,否则会造成资源泄漏,比如Stack类。

4. 拷贝构造函数

4.1 拷贝构造函数的概念

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

4.2 拷贝构造函数的特性

  1. 拷贝构造函数是构造函数的一个重载形式。
  2. 自定义类型传值传参前,编译器会先自动调用拷贝构造函数,再调用函数。(传引用传参不用调用拷贝构造)
class Date
{
public:
	Date(int year = 1, 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;
	}

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

private:
	int _year;
	int _month;
	int _day;
};
void func1(Date d)
{

}
void func2(Date& rd)
{

}
int main()
{
	Date d1(2024, 1, 28);
	// C++规定自定义的类型都会调用拷贝构造
	func1(d1);
	func2(d1);

	return 0;
}
  1. 拷贝构造函数只能有一个且必须是类类型对象的引用,使用传值参数编译器会报错,因为会引发无穷递归。
    在这里插入图片描述
    引发无穷递归是无法解决的,因此拷贝构造函数参数必须是引用。
  2. 若是没由显示定义,编译器会生成默认的拷贝构造函数。默认的拷贝构造函数对内置类型成员按内存存储字节序来完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝。
class Date
{
public:
	Date(int year = 1, 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;
	}

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

private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1(2024, 1, 28);
	Date d2(d1);
    
    d1.Print();
    d2.Print();

	return 0;
}

在这里插入图片描述

  1. 编译器默认生的拷贝函数可以按字节序存储拷贝,但是并不是任何的类型都适合浅拷贝。一旦涉及到资源开辟时,浅拷贝就不控制了。
    例如:
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 st1;
	Stack st2(st1);

	return 0;
}

在这里插入图片描述

我们通过监视窗口可以发现st2是st1的拷贝,st2中的_array和st1中的_array所指向的空间是一致的。但编译器调用析构函数时,st2中的_array所指向的空间被释放,st1中的_array就成了野指针了。当st1被析构函数释放,就造成了同一块空间释放了两次。
要解决这个问体就只能使用深拷贝。深拷贝没有固定的写法,深拷贝是要跟各自的类型是有关系的。

 //深拷贝
	Stack(const Stack& s)                                                                                                                                                                                                                            
	{
		DataType* tmp = (DataType*)malloc(s._capacity *(sizeof(DataType)));
		if (tmp == nullptr)
		{
			perror("malloc fail");
			exit(-1);
		}

		memcpy(tmp, s._array, sizeof(DataType) * s._size);

		_array = tmp;
		_size = s._size;
		_capacity = s._capacity;
	}

因此我们可以得出:类中如果没有涉及资源申请时,拷贝构造函数是否写都可以;一旦涉及到资源申请时,则拷贝构造函数是一定要写的,否则就是浅拷贝。

5. 赋值运算符重载

5.1 运算符重载

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

注意:

  1. 不能通过连接其他符号来创建新的操作符。
  2. 重载操作符必须有一个类类型参数。
  3. 用于内置类的运算符,其含义不变。
  4. 作为成员函数重载时,其形参看起来比操作数数目少1,原因是成员函数的第一个参数为隐含的this指针。
  5. .* :: sizeof ?: . 注意以上5个运算符不能重载。
class Date
{ 
public:
 Date(int year = 1900, int month = 1, int day = 1)
   {
        _year = year;
        _month = month;
        _day = day;
   }
    
    // bool operator==(Date* this, const Date& d2)
    // 这里需要注意的是,左操作数是this,指向调用函数的对象
    bool operator==(const Date& d2)
    {
        return _year == d2._year;
            && _month == d2._month
            && _day == d2._day;
    }
private:
 int _year;
 int _month;
 int _day;
};

5.2 赋值运算符重载

  1. 赋值运算符重载格式:
  • 参数类型: const 类名& ,传引用可以提高传参效率。

  • 返回值类型 类名& ,返回引用可以提高返回值的效率,有返回值的目的是为了支持连续的赋值。

  • 检测是否自己给自己赋值。

  • 返回*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 ;
};
  1. 赋值运算符值能重载成类的成员函数不能重载成全局函数。
    原因是赋值运算符不显示实现,编译器会生成一个默认的。若用户再类外生成自己的一个全局赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值运算符重载只能是类的成员函数。
class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	int _year;
	int _month;
	int _day;
};

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. 用户没有显示实现赋值运算符重载,编译器会生成一个默认的赋值运算符重载,以值的方式逐字节拷贝。注意:内置类型成元变量是直接赋值的,自定义类型成员变量需要调用对应类的赋值运算符重载完成赋值。

6. Date类实现

class Date
{
public:
	// 获取某年某月的天数
	int GetMonthDay(int year, int month)
	{
		assert(month > 0 && month <= 12);
		static int days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		int day = days[month];
		if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
		{
			day =29;
		}
		return day;
	}

	// 全缺省的构造函数
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;

	}
	// 拷贝构造函数
 // d2(d1)
	Date(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}

	// 赋值运算符重载
 // d2 = d3 -> d2.operator=(&d2, d3)
	Date& operator=(const Date& d)
	{
		if (*this !=d )
		{
			_year = d._year;
			_month = d._month;
			_day = d._day;
		}

		return *this;
	}
	
	 日期+=天数
	Date& operator+=(int day)
	{
		_day += day;

		while (_day > GetMonthDay(_year, _month))
		{
			_day -= GetMonthDay(_year, _month);
			++_month;
			if (_month > 12)
			{
				++_year;
			}
		}
		return *this;
	}
	// 日期+天数
	Date operator+(int day)
	{
		Date tmp(*this);
		tmp += day;
		return tmp;
	}
	// 日期-天数
	Date operator-(int day)
	{
		Date tmp(*this);
		tmp -= day;
		return tmp;

	}
	 日期-=天数
	Date& operator-=(int day)
	{
		_day -= day;
		while (_day <= 0)
		{
			
			--_month;
			if (_month == 0)
			{
				--_year;
				_month = 12;
			}
			_day += GetMonthDay(_year, _month);
		}
		return *this;
	}
	 前置++
	Date& operator++()
	{
		*this += 1;
		return *this;
	}
	 后置++
	Date operator++(int)
	{
		Date tmp(*this);
		*this += 1;
		return tmp;
	}
	 后置--
	Date operator--(int)
	{
		Date tmp(*this);
		*this -= 1;
		return tmp;
	}
	 前置--
	Date& operator--()
	{
		*this -= 1;
		return *this;
	}
	// >运算符重载
	bool operator>(const Date& d)
	{
		return !(*this <= d);
	}
	// ==运算符重载
	bool operator==(const Date& d)
	{
		return _year == d._year
			&& _month == d._month
			&& _day == d._day;

	}
	// >=运算符重载
	bool operator >= (const Date& d)
	{
		return !(*this < d);
	}

	// <运算符重载
	bool operator < (const Date& d)
	{
		if (_year < d._year)
		{
			return true;
		}
		else if (_year == d._year)
		{
			if (_month < d._month)
			{
				return true;
			}
			else if (_month == d._month)
			{
				if (_day < d._day)
				{
					return true;
				}
			}
		}
		return false;

	}
	// <=运算符重载
	bool operator <= (const Date& d)
	{
		return *this < d || *this == d;
	}
	// !=运算符重载
	bool operator != (const Date& d)
	{
		return !(*this == d);
	}
	 日期-日期 返回天数
	int operator-(const Date& d)
	{
		int flag = 1;
		Date max = *this;
		Date min = d;
		if (*this < d)
		{
			flag = -1;
			max = d;
			min = *this;
		}

		int n = 0;
		while (min != max)
		{
			++min;
			++n;
		}

		return n * flag;
	}

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

private:
	int _year;
	int _month;
	int _day;
};
  • 12
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值