【C++】类和对象 中

类的默认成员函数

默认成员函数就是用户没有显式实现,编译器会自动生的成员函数称为默认成员函数。⼀个类,我 们不写的情况下编译器会默认生成以下6个默认成员函数,需要注意的是这6个中最重要的是前4个

1.构造函数

构造函数主要完成初始化工作。构造函数的本质是要替代以前Stack和Date类中写的Init函数的功能,构造函数自动调用的特点就完美的替代的了Init。

构造函数的特点:

  1. 函数名与类名相同。
  2. 无返回值。(返回值啥都不需要给,也不需要写void)
  3. 对象实例化时系统会自动调用对应的构造函数。
  4. 构造函数可以重载。
  5. 如果类中没有显式定义构造函数,则C++编译器会自动生成⼀个无参的默认构造函数,⼀旦用户显式定义编译器将不再生成。
  6. 无参构造函数、全缺省构造函数、我们不写构造时编译器默认生成的构造函数,都叫做默认构造函 数。但是这三个函数有且只有⼀个存在,不能同时存在。无参构造函数和全缺省构造函数虽然构成 函数重载,但是调用时会存在歧义。要注意很多同学会认为默认构造函数是编译器默认生成那个叫 默认构造,实际上无参构造函数、全缺省构造函数也是默认构造,总结⼀下就是不传实参就可以调 用的构造就叫默认构造。
  7. 我们不写,编译器默认生成的构造,对内置类型成员变量的初始化没有要求,也就是说是是否初始化是不确定的,看编译器。对于自定义类型成员变量,要求调用这个成员变量的默认构造函数初始 化。如果这个成员变量,没有默认构造函数,那么就会报错,我们要初始化这个成员变量,需要用初始化列表才能解决,初始化列表。

这里更推荐使用全缺省函数,可以把上面的两种结合起来。

2.析构函数

析构函数与构造函数功能相反,析构函数主要完成清理工作,析构函数不是完成对对象本身的销毁,他有点像之前实现数据结构的destroy工具(类似于free)。C++规定对象在销毁时会自动调用析构函数,完成对象中资源的清理释放工作。我们创建的Date没有 Destroy,其实就是没有资源需要释放,所以严格说Date是不需要析构函数的。

析构函数的特点

  1. 析构函数名是在类名前加上字符 ~。 
  2. 无参数无返回值。(这里跟构造类似,也不需要加void)
  3. ⼀个类只能有⼀个析构函数。若未显式定义,系统会自动生成默认的析构函数。
  4. 对象生命周期结束时,系统会自动调用析构函数。
  5. 跟构造函数类似,我们不写编译器自动生成的析构函数对内置类型成员不做处理,自定类型成员会 调用他的析构函数。
  6. 还需要注意的是我们显示写析构函数,对于自定义类型成员也会调用他的析构,也就是说自定义类 型成员无论什么情况都会自动调用析构函数。
  7. 如果类中没有申请资源时,析构函数可以不写,直接使用编译器生成的默认析构函数,如Date;如果默认生成的析构就可以用,也就不需要显示写析构,如MyQueue;但是有资源申请时,⼀定要自己写析构,否则会造成资源泄漏,如Stack。
  8. ⼀个局部域的多个对象,C++规定后定义的先析构
#include<iostream>
using namespace std;
//date不需要析构
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
    ~Date()
	{
		cout<<"~Date()"<<endl;
	}
	void Print()
	{
		cout << _year << "." << _month << "." << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

//栈
typedef int STDataType;
class Stack
{
public:
	Stack(int n = 4)
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (nullptr == _a)
		{
			perror("malloc申请空间失败");
			return;
		}
		_capacity = n;
		_top = 0;
	}
	~Stack()
	{
		cout << "~Stack()" << endl;
		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}
private:
	STDataType* _a;
	size_t _capacity;
	size_t _top;
};

class MyQueue
{
public:
	//编译器默认⽣成MyQueue的析构函数调⽤了Stack的析构,释放的Stack内部的资源 
    // 显⽰写析构,也会⾃动调⽤Stack的析构 
    //~MyQueue()
    //{}
private:
	Stack pushst;
	Stack popst;
};

int main()
{
	Stack st;
	MyQueue mq;
	return 0;
}

3.拷贝构造函数

拷贝构造是使用同类对象初始化创建对象

如果⼀个构造函数的第⼀个参数是自身类类型的引用,且任何额外的参数都有默认值,则此构造函数也叫做拷贝构造函数,也就是说拷贝构造是⼀个特殊的构造函数。

拷贝构造的特点:

  1. 拷贝构造函数是构造函数的⼀个重载。
  2. 拷贝构造函数的第⼀个参数必须是类类型对象的引用,使用传值方式编译器直接报错,因为语法逻辑上会引发无穷递归调用。拷贝构造函数也可以多个参数,但是第⼀个参数必须是类类型对象的引用,后面的参数必须有缺省值。
  3. C++规定自定义类型对象进行拷贝行为必须调用拷贝构造,所以这里自定义类型传值传参和传值返回都会调用拷贝构造完成。
  4. 若未显式定义拷贝构造,编译器会生成自动生成拷贝构造函数。自动生成的拷贝构造对内置类型成员变量会完成值拷贝/浅拷贝(⼀个字节⼀个字节的拷贝),对自定义类型成员变量会调用他的拷贝构造。
  5. 像Date这样的类成员变量全是内置类型且没有指向什么资源,编译器自动生成的拷贝构造就可以完成需要的拷贝,所以不需要我们显示实现拷贝构造。像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器自动生成的拷贝构造完成的值拷贝/浅拷贝不符合我们的需求,所以需要我们自己实现深拷贝(对指向的资源也进行拷贝)。像MyQueue这样的类型内部主要是自定义类型 Stack成员,编译器自动生成的拷贝构造会调用Stack的拷贝构造,也不需要我们显示实现 MyQueue的拷贝构造。这里还有⼀个小技巧,如果⼀个类显示实现了析构并释放资源,那么他就需要显示写拷贝构造,否则就不需要。
  6. 传值返回会产生⼀个临时对象调用拷贝构造,传值引用返回,返回的是返回对象的别名(引用),没有产生拷贝。但是如果返回对象是⼀个当前函数局部域的局部对象,函数结束就销毁了,那么使用引用返回是有问题的,这时的引用相当于⼀个野引用,类似⼀个野指针⼀样。传引用返回可以减少拷贝,但是⼀定要确保返回对象,在当前函数结束后还在,才能用引用返回。
#include<iostream>
using namespace std;
class Date
{
public:
	//全缺省构造函数 
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	//d2(d1)
    //利用引用实现拷贝构造
	Date(Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}

    //利用指针也可实现类似效果
    //但其实其本质是构造
	Date(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(2025,4,24);//构造
	Date d2(d1);       //拷贝构造
	Date d3 = d1;      //拷贝构造

	Date d4(&d1);      //构造
	Date d5 = &d1;     //构造
	return 0;
}

栈与队列:

typedef int STDataType;
class Stack
{
public:
	Stack(int n = 4)
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (nullptr == _a)
		{
			perror("malloc申请空间失败");
			return;
		}
		_capacity = n;
		_top = 0;
	}
	Stack(const Stack& st)
	{
		// 需要对_a指向资源创建同样⼤的资源再拷⻉值 
		_a = (STDataType*)malloc(sizeof(STDataType) * st._capacity);
		if (nullptr == _a)
		{
			perror("malloc申请空间失败!!!");
			return;
		}
		memcpy(_a, st._a, sizeof(STDataType) * st._top);
		_top = st._top;
		_capacity = st._capacity;
	}


	void Push(const STDataType& x)
	{
		//扩容略。。。。
		_a[_top] = x;
		_top++;
	}

	int Top()
	{
		return _a[_top - 1];
	}

	~Stack()
	{
		cout << "~Stack()" << endl;
		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}
private:
	STDataType* _a;
	size_t _capacity;
	size_t _top;
};

class MyQueue
{
public:
	
private:
	Stack pushst;
	Stack popst;
};

int main()
{
	Stack st1;
	st1.Push(1);
	st1.Push(2);
	// Stack不显⽰实现拷⻉构造,⽤⾃动⽣成的拷⻉构造完成浅拷⻉ 
	// 会导致st1和st2⾥⾯的_a指针指向同⼀块资源,析构时会析构两次,程序崩溃 
	Stack st2 = st1;
	MyQueue mq1;
	// MyQueue⾃动⽣成的拷⻉构造,会⾃动调⽤Stack拷⻉构造完成pushst/popst 
	// 的拷⻉,只要Stack拷⻉构造⾃⼰实现了深拷⻉,他就没问题 
	MyQueue mq2 = mq1;
	return 0;
}

当使用传引用返回时,返回的对象会进行析构,造成了野引用的现象,而使用传值返回时,类会进行拷贝构造

int& f1()
{
	int ret = 0;
	return ret;
}
Stack& f2()
{
	Stack st;
	st.Push(1);
	st.Push(2);
	st.Push(3);

	return st;
}
int main()
{
	cout << f1() << endl;
	cout << f2().Top() << endl;//f2中的st已被销毁
	return 0;
}

//正确写法
Stack f2()
{
	Stack st;
	st.Push(1);
	st.Push(2);
	st.Push(3);

	return st;
}

4.赋值重载

赋值重载主要是把一个对象赋值给另一个对象

4.1运算符重载

  • 当运算符被用于类类型的对象时,C++语言允许我们通过运算符重载的形式指定新的含义。C++规 定类类型对象使用运算符时,必须转换成调用对应运算符重载,若没有对应的运算符重载,则会编译报错。
  • 运算符重载是具有特殊名字的函数,他的名字是由operator和后⾯要定义的运算符共同构成。和其 他函数⼀样,它也具有其返回类型和参数列表以及函数体。
  • 重载运算符函数的参数个数和该运算符作用的运算对象数量⼀样多。一元运算符有⼀个参数,二元 运算符有两个参数,二元运算符的左侧运算对象传给第⼀个参数,右侧运算对象传给第二个参数。
  • 如果⼀个重载运算符函数是成员函数,则它的第⼀个运算对象默认传给隐式的this指针,因此运算 符重载作为成员函数时,参数比运算对象少⼀个。
  • 运算符重载以后,其优先级和结合性与对应的内置类型运算符保持⼀致。
  • 不能通过连接语法中没有的符号来创建新的操作符:比如operator@。
  • .*  ::  sizeof   ?:  .   注意以上5个运算符不能重载。
  • 重载操作符至少有⼀个类类型参数,不能通过运算符重载改变内置类型对象的含义,如: int operator+(int x, int y)
  • ⼀个类需要重载哪些运算符,是看哪些运算符重载后有意义,比如Date类重载operator-就有意义,但是重载operator+就没有意义。
  • 重载++运算符时,有前置++和后置++,运算符重载函数名都是operator++,无法很好的区分。 C++规定,后置++重载时,增加⼀个int形参,跟前置++构成函数重载,方便区分。
  • 重载>时,需要重载为全局函数,因为重载为成员函数,this指针默认抢占了第⼀个形参位置,第⼀个形参位置是左侧运算对象,调用时就变成了对象
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	void Print()
	{
		cout << _year << "." << _month << "." << _day << endl;
	}
//private:
	int _year;
	int _month;
	int _day;
};

bool operator==(const Date& x1,const Date& x2)
{//加引用减少拷贝
	return x1._year == x2._year
		&& x1._month == x2._month
		&& x1._day == x2._day;
}

int main()
{
	int i = i, j = 2;
	bool ret1 = i < j;
	i++;
	
	Date d1(2025, 8, 2);
	Date d2(2025, 8, 3);
	//bool ret2 = d1 == d2; 
	cout << (d1 == d2) << endl;
	cout<<(operator==(d1, d2)) << endl;
	return 0;
}

不过目前还有点瑕疵,为了可以使用类的成员变量,我们直接把他们public了,这种方法太low了,以下有三种方法:

1.提供Getxxx函数
2.友元friend
3.直接放到类里面

前两个在现在看来有些超标,这里更推荐第三种。

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

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

    //这里要注意,经过之前的学习,类里面的函数隐藏着this,所以这里只用传一个参数。
	bool operator==(const Date& x2)
	{
		return _year == x2._year
			&& _month == x2._month
			&& _day == x2._day;
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	int i = i, j = 2;
	bool ret1 = i < j;
	i++;
	
	Date d1(2025, 8, 2);
	Date d2(2025, 8, 3);

	cout << (d1 == d2) << endl;
	cout<<(d1.operator==(d2)) << endl;
    //当有两个变量时 左边的变量传左边,右边的传右边,不要写反
	return 0;
}

4.2赋值运算符重载

赋值运算符重载是⼀个默认成员函数,用于完成两个已经存在的对象直接的拷贝赋值,这里要注意跟拷贝构造区分,拷贝构造用于⼀个对象拷贝初始化给另一个要创建的对象。

赋值运算符重载的特点:

  1. 赋值运算符重载是⼀个运算符重载,规定必须重载为成员函数。赋值运算重载的参数建议写成 const 当前类类型引用,否则会传值传参会有拷贝
  2. 有返回值,且建议写成当前类类型引用,引用返回可以提高效率,有返回值目的是为了支持连续赋 值场景。
  3. 没有显式实现时,编译器会自动生成⼀个默认赋值运算符重载,默认赋值运算符重载行为跟默认拷 贝构造函数类似,对内置类型成员变量会完成值拷贝/浅拷贝(⼀个字节⼀个字节的拷贝),对自定义 类型成员变量会调用他的赋值重载函数。
  4. 像Date这样的类成员变量全是内置类型且没有指向什么资源,编译器自动生成的赋值运算符重载就 可以完成需要的拷贝,所以不需要我们显示实现赋值运算符重载。像Stack这样的类,虽然也都是 内置类型,但是_a指向了资源,编译器自动生成的赋值运算符重载完成的值拷贝/浅拷贝不符合我 们的需求,所以需要我们自己实现深拷贝(对指向的资源也进行拷贝)。像MyQueue这样的类型内部 主要是自定义类型Stack成员,编译器自动生成的赋值运算符重载会调用Stack的赋值运算符重载, 也不需要我们显示实现MyQueue的赋值运算符重载。这里还有⼀个小技巧,如果⼀个类显示实现 了析构并释放资源,那么他就需要显示写赋值运算符重载,否则就不需要。
class Date
{
public:
	int GetMonthDay(int year, int month)
	{
		assert(month > 0 && month < 31);
		//静态数组
		static int monthDayArray[13] = { -1,31,28,31,30,31,30,31,31,30,31,30,31 };
		if (month == 2&&(year % 400 == 0)||(year%4==0&&year%100!=0))
		{
			return 29;
		}
		else
		{
			return monthDayArray[month];
		}
	}

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

    //拷贝构造
	Date(const Date& d)
	{ }

    // 赋值运算符
	// 传引⽤返回减少拷⻉ 
    // d1 = d2;
	Date& operator=(const Date& d)
	{
		// 不要检查⾃⼰给⾃⼰赋值的情况 
		if (this != &d)
		{
			_year = d._year;
			_month = d._month;
			_day = d._day;
		}
		// d1 = d2表达式的返回对象应该为d1,也就是*this 
		return *this;
	}


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


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

int main()
{
	Date d1(2025,8,2);
	//拷贝构造,一个已经存在的对象初始化另一个对象
	//Date d2(d1);
	Date d2 = d1;
	Date d3(2025, 8, 4);

	//已经存在的两个对象之间的拷贝
	//d1 = d3;
	d1.operator=(d3);

	d1 = d2 = d3;
	
	d1.Print();
	d2.Print();
	d3.Print();

	return 0;
}

4.3日期类实现

现在利用学习的知识,完成一个日期计算器。

//Date.h
#pragma once
#include<iostream>
#include<assert.h>
using namespace std;

//首先定义一个Date类
class Date
{
public:
	friend ostream& operator<<(ostream& out, const Date& d);//友元
	friend istream& operator>>(istream& in, Date& d);// 为了可以调用成员参数,可以不管
    //首先需要知道某个月有几天
	int GetMonthDay(int year, int month)
	{
		//cout<<"&" << endl;
		assert(month > 0 && month < 13);
		//静态数组 //直接通过数组来判断一个月中有几天。
		static int monthDayArray[13] = { -1,31,28,31,30,31,30,31,31,30,31,30,31 };
		if (month == 2&&((year % 400 == 0)||(year%4==0&&year%100!=0)))
		{
			return 29;//闰年二月
		}
		else
		{
			return monthDayArray[month];
		}
	}

	Date(int year = 1, int month = 1, int day = 1);//构造函数

	// 传引⽤返回减少拷⻉ 
    // d1 = d2;
	Date& operator=(const Date& d)
	{
		// 不要检查⾃⼰给⾃⼰赋值的情况 
		if (this != &d)
		{
			_year = d._year;
			_month = d._month;
			_day = d._day;
		}
		// d1 = d2表达式的返回对象应该为d1,也就是*this 
		return *this;
	}
    //判断日期是否有效
	bool CheckDate();
    //打印工具
	void Print();

    //日期加天数
    //d1 += 100;
	Date& operator+=(int day);
    //d1 + 100;
	Date operator+(int day);

	//日期减天数
	Date& operator -(int day);
	Date& operator -= (int day);
	//日期减日期
	int operator-(const Date& d);

	bool operator==(const Date& d);
	bool operator!=(const Date& d);
	bool operator<(const Date& d);
	bool operator<=(const Date& d);
	bool operator>(const Date& d);
	bool operator>=(const Date& d);

	//d1++
	Date operator++(int);
	//++d1
	Date& operator++();
	//d1--
	Date operator--(int);
	//--d1
	Date& operator--();
private:
	int _year;
	int _month;
	int _day;
};

接下来就是具体功能的实现了。

//Datec.cpp
#include"Date.h"

bool Date::CheckDate()
{
	if (_month < 1 || _month>12 || _day<1 || _day>GetMonthDay(_year, _month))
	{
		return false;
	}
	else
	{
		return true;
	}
}

void Date::Print()
{
	cout << _year << "." << _month << "." << _day << endl;
}

Date::Date(int year, int month, int day)
{
	_year = year;
	_month = month;
	_day = day;

	if (!CheckDate())
	{
		cout << "非法日期->" <<*this<<endl;
	}
}

//d1 += 100
Date& Date :: operator+=(int day)
{
	if (day < 0)//day = -100;
	{           //d1 -= 100;
		return *this  -= -day;
	}
	_day += day;
	//进位
	while (_day > GetMonthDay(_year,_month))
	{
		_day -= GetMonthDay(_year, _month);
		++_month;
		if (_month == 13)
		{
			++_year;
			_month = 1;
		}
	}
	return *this;
}

//d1+100
Date Date::operator+(int day)
{
	Date tmp(*this);
	tmp += day;//直接通过赋值重载实现。
	return tmp;
}

//日期减天数
Date& Date::operator -=(int day)
{
	if (day < 0)
	{          
		return *this += -day;
	}
	_day -= day;
	//借位
	while (_day <= 0)
	{
		--_month;
		if (_month == 0)
		{
			_month = 12;
			--_year;
		}
		_day += GetMonthDay(_year, _month);
	}
	return *this;
}

Date& Date::operator-(int day)
{
	Date tmp(*this);
	tmp -= day;
	return tmp;
}

//日期减日期
int Date::operator-(const Date& d)
{
	Date max = *this;
	Date min = d;
	int flag = 1;
	if (*this < d)//先找到谁大谁小
	{
		max = d;
		min = *this;
		flag = -1;
	}

	int n = 0;
	while (min != max)//直接暴力计算
	{
		++min;
		++n;
	}
	return n;
}

//要多通过寻找逻辑关系,然后结合赋值重载实现。
//d1++
Date Date::operator++(int)
{
	Date tmp(*this);
	*this += 1;
	return tmp;
}

//++d1
Date& Date::operator++()
{
	*this += 1;
	return *this;
}

//d1--
Date Date::operator--(int)
{
	Date tmp(*this);
	*this -= 1;
	return tmp;
}

//--d1
Date& Date::operator--()
{
	*this -= 1;
	return *this;
}

bool Date::operator==(const Date& d)
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

bool Date::operator!=(const Date& d)
{
	return !(*this == d);
}
bool Date::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;
	}
	return false;
}
bool Date::operator<=(const Date& d)
{
	return *this < d || *this == d;
}
bool Date::operator>(const Date& d)
{
	return !(*this <= d);
}
bool Date::operator>=(const Date& d)
{
	return !(*this < d);
}

//cout<<d1
ostream& operator<<(ostream& out, const Date& d)
{
	out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
	return out;
}

//cin>>d1
istream& operator>>(istream& in, Date& d)
{
	while(1)
	{
		cout << "请依次输入年月日:";
		in >> d._year >> d._month >> d._day;
		if (d.CheckDate())
		{
			break;
		}
		else
		{
			cout << "非法日期,请重新输入:";
		}
	}
	return in;
}

最后调试修改,确保没问题

//test.cpp
#include"Date.h"

void test()
{
	Date d1(2025, 8, 2);
	//拷贝构造,一个已经存在的对象初始化另一个对象
	//Date d2(d1);
	Date d2 = d1;
	Date d3(2025, 8, 4);

	//已经存在的两个对象之间的拷贝
	//d1 = d3;
	d1.operator=(d3);

	d1 = d2 = d3;

	d1.Print();
	d2.Print();
	d3.Print();
}

void test01()
{
	Date d1(2025, 8, 2);
	Date d2 = d1 + 10000;
	d1.Print();
	d2.Print();

	Date d3 = d1 += 10000;
	d1.Print();
	d2.Print();
}

void test02()
{
	Date d1(2025, 8, 2);
	Date d2 = d1 -= 10000;
	d1.Print();
	d2.Print();

	Date d3(2025, 8, 2);
	Date d4 = d3 - 10000;
	d3.Print();
	d4.Print();

	Date d5(2025, 8, 2);
	d5 += -100;
	d5.Print();
}

void test03()
{
	Date d1(2025, 8, 2);
	Date d2 = d1++;
	d1.Print();
	d2.Print();

	Date d3(2025, 8, 2);
	Date d4 = ++d3;
	d3.Print();
	d4.Print();
}

void test04()
{
	Date d1(2006, 4, 21);
	Date d2(2005, 9, 23);

	cout << (d1 < d1) << endl;
	cout << (d1 > d1) << endl;
	cout << (d1 == d1) << endl;
}

void test05()
{
	Date d1;
	cin >> d1;
	cout << d1;
}

void test06()
{

	Date d1;
	Date d2;
	cout << "开始日期:" << endl;;
	cin >> d1;
	cout << "结束日期:" << endl;;
	cin >> d2;

	cout << "相差天数:" <<d2-d1 <<" 天" << endl;
}

void test07()
{
	int year1 = 0, month1 = 0, day1 = 0;
	int day;
	Date d1;
	cout << "开始日期:" << endl;
	cin >> d1;
	cout << "距离天数:";
	cin >> day;
	Date d2 = d1 + day;
	cout << "结束日期:"<<d2;
	//d2.Print();
}

int main()
{
	while (1)
	{
		cout << "--------------------------" << endl;
		cout << "        日期计算器        " << endl;
		cout << "1.计算两个日期间相差多少天" << endl;
		cout << "2.    推算几天后的日期    " << endl;
		cout << "3.          退出          " << endl;
		cout << "--------------------------" << endl;
		cout << "请选择:";
		int flag = 0;
		cin >> flag;
		if (flag == 1)
		{
			test06();
			cout << endl;
		}
		else if (flag == 2)
		{
			test07();
			cout << endl;
		}
		else if(flag ==3 )
		{
			break;
		}
		else
		{
			cout << "无效输入,请从新输入!!" << endl;
			continue;
		}
	}
	cout << "已退出" << endl;
	return 0;
}

5.取地址运算符重载

5.1 const成员函数

将const修饰的成员函数称之为const成员函数,const修饰成员函数放到成员函数参数列表的后 ⾯。

const实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。 const 修饰Date类的Print成员函数,Print隐含的this指针由 Date* const this 变为 const Date* const this

class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
    // void Print(const Date* const this) const
	void Print() const
	{
		cout << _year << "." << _month << "." << _day << endl;
	}

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

int main()
{
	// 这⾥⾮const对象也可以调⽤const成员函数是⼀种权限的缩⼩ 
	Date d1(2024, 7, 5);
	d1.Print();
	const Date d2(2024, 8, 5);
	d2.Print();
	return 0;

}

只要不改变调用对象的函数都建议加const

//Date.h
class Date
{
public:
	......
	void Print() const;

    //d1 += 100;
	//Date& operator+=(int day);
    //d1 + 100;
	Date operator+(int day) const;

	//日期减天数
	Date& operator -(int day) const;
	//Date& operator -= (int day);
	//日期减日期
	//int operator-(const Date& d);

	bool operator==(const Date& d) const;
	bool operator!=(const Date& d) const;
	bool operator<(const Date& d) const;
	bool operator<=(const Date& d) const;
	bool operator>(const Date& d) const;
	bool operator>=(const Date& d) const;

	//d1++
	//Date operator++(int);
	//++d1
	//Date& operator++();
	//d1--
	//Date operator--(int);
	//--d1
	//Date& operator--();
private:
	int _year;
	int _month;
	int _day;
};
//Datec.cpp
#include"Date.h"

/*
bool Date::CheckDate()
{
	if (_month < 1 || _month>12 || _day<1 || _day>GetMonthDay(_year, _month))
	{
		return false;
	}
	else
	{
		return true;
	}
}
*/

void Date::Print() const
{
	cout << _year << "." << _month << "." << _day << endl;
}

/*
Date::Date(int year, int month, int day)
{
	_year = year;
	_month = month;
	_day = day;

	if (!CheckDate())
	{
		cout << "非法日期->" <<*this<<endl;
	}
}


//d1 += 100
Date& Date :: operator+=(int day)
{
	if (day < 0)//day = -100;
	{           //d1 -= 100;
		return *this  -= -day;
	}
	_day += day;
	//进位
	while (_day > GetMonthDay(_year,_month))
	{
		_day -= GetMonthDay(_year, _month);
		++_month;
		if (_month == 13)
		{
			++_year;
			_month = 1;
		}
	}
	return *this;
}
*/

//d1+100
Date Date::operator+(int day) const
{
	Date tmp(*this);
	tmp += day;//直接通过赋值重载实现。
	return tmp;
}

/*
//日期减天数
Date& Date::operator -=(int day)
{
	if (day < 0)
	{          
		return *this += -day;
	}
	_day -= day;
	//借位
	while (_day <= 0)
	{
		--_month;
		if (_month == 0)
		{
			_month = 12;
			--_year;
		}
		_day += GetMonthDay(_year, _month);
	}
	return *this;
}
*/

Date& Date::operator-(int day) const
{
	Date tmp(*this);
	tmp -= day;
	return tmp;
}

/*
//日期减日期
int Date::operator-(const Date& d)
{
	Date max = *this;
	Date min = d;
	int flag = 1;
	if (*this < d)//先找到谁大谁小
	{
		max = d;
		min = *this;
		flag = -1;
	}

	int n = 0;
	while (min != max)//直接暴力计算
	{
		++min;
		++n;
	}
	return n;
}


//要多通过寻找逻辑关系,然后结合赋值重载实现。
//d1++
Date Date::operator++(int)
{
	Date tmp(*this);
	*this += 1;
	return tmp;
}

//++d1
Date& Date::operator++()
{
	*this += 1;
	return *this;
}

//d1--
Date Date::operator--(int)
{
	Date tmp(*this);
	*this -= 1;
	return tmp;
}

//--d1
Date& Date::operator--()
{
	*this -= 1;
	return *this;
}
*/

bool Date::operator==(const Date& d) const
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

bool Date::operator!=(const Date& d) const
{
	return !(*this == d);
}
bool Date::operator<(const Date& d) const
{
	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;
	}
	return false;
}
bool Date::operator<=(const Date& d) const
{
	return *this < d || *this == d;
}
bool Date::operator>(const Date& d) const
{
	return !(*this <= d);
}
bool Date::operator>=(const Date& d) const
{
	return !(*this < d);
}

/*
//cout<<d1
ostream& operator<<(ostream& out, const Date& d)
{
	out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
	return out;
}

//cin>>d1
istream& operator>>(istream& in, Date& d)
{
	while(1)
	{
		cout << "请依次输入年月日:";
		in >> d._year >> d._month >> d._day;
		if (d.CheckDate())
		{
			break;
		}
		else
		{
			cout << "非法日期,请重新输入:";
		}
	}
	return in;
}
*/

5.2取地址运算符重载

取地址运算符重载分为普通取地址运算符重载const取地址运算符重载,⼀般这两个函数编译器自动生成的就可以够我们用了,不需要去显示实现。除非一些很特殊的场景,比如我们不想让别人取到当前类对象的地址,就可自己实现⼀份,胡乱返回⼀个地址。

class Date
{
public:
	Date* operator&()
	{
		return this;
		// return nullptr;
	}

	const Date* operator&()const
	{
		return this;
		// return nullptr;
	}
private:
	int _year; // 年 
	int _month; // ⽉ 
	int _day; // ⽇ 
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值