类和对象(中)

类和对象(中)

一、类的默认成员函数

默认成员函数就是用户没有显示实现,编译器会自动生成的成员函数称为默认成员函数。一个类,我们不写的情况下编译器会默认生成一下6个默认成员函数初始化和清理和拷贝赋值比较重要,取地址重载不重要,C++11还增加了两个默认成员变量,移动构造和移动赋值。

在这里插入图片描述

但是,大多数情况下,编译器是无法自动生成与我们需求完全一致的默认成员函数,这就需要我们自己来进行编写。

二、构造函数

构造函数时特殊的成员函数,构造函数虽然叫构造,但是主要任务并不是开空间创建对象(对象实例化就已经完成了栈帧的创建,空间就开好了),而是对象实例化时初始化对象。构造函数的本质是要替代我们以前Init成员函数的功能。

构造函数的特点:

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

构造函数有三种:无参、带参、 带参缺省(无参和全缺省为默认构造函数)

// 无参
Date()
{
    _year = 1900;
    _month = 1;
    _day = 1;
}
...
    
//实例化+初始化
Date d1;		// 调用无参的构造函数,不能采用Date d1()
// 带参
Date(int year, int month, int day)
{
    _year = year;
    _month = month;
    _day = day;
}
...
    
//实例化+初始化
Date d1(2024, 7, 24);		// 调用带参的构造函数,采用Date d1(构造函数的实参)
// 带参 + 缺省
Date(int year = 1900, int month = 1, int day = 1)
{
    _year = year;
    _month = month;
    _day = day;
}
...
    
//实例化+初始化
Date d1(2024, 7, 24);		// 调用带参的构造函数,采用Date d1(构造函数的实参)
d1.Print();		// 2024 7 24
Date d2(2024);
d2.Print();		// 2024 1 1
Date d3;		// 若想全缺省传参则直接Date d2, 不能采用Date d2()
d3.Print();		// 1900 1 1	

示例一:

#include <iostream>
using namespace std;

class Date
{
public:
	Date()	// 无参
	{
		_year = 1;
		_month = 1;
		_day = 1;
	}

    Date(int year, int month, int day)	// 带参,函数重载
	{
    	_year = year;
    	_month = month;
   		_day = day;
	}	
	void Print()
	{
		cout << _year << " " << _month << " " << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1;	// 调用无参的构造函数,不能采用Date d1()
	d1.Print();	
	return 0;
}

输出结果:

1 1 1
    

示例二(默认构造的巧妙运用地方,特点7):

下面Queue类就是直接采用编译器自动生成的默认构造函数,并且也符合预期目的。还有一种就是C++11采用的缺省成员变量来实现。

#include <iostream>
using namespace std;
typedef int STDataType;
class Stack
{
public:
	Stack(int n = 4)	// 全缺省构造函数为默认构造
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (_a == nullptr)
		{
			perror("malloc error");
			return;
		}
		_capacity = n;
		_top = 0;
	}
private:
	STDataType* _a;
	int _top;
	int _capacity;
};

class Queue		// 采用两个栈模拟队列
{
public:
	// 编译器默认生成MyQueue的构造函数调用了Stack的构造,完成了两个成员的初始化
private:
	Stack pushst;
	Stack popst;
};

int main()
{
	Queue q1;
	return 0;
}

调试窗口:
在这里插入图片描述

我们可以看到,编译器不但没有报错,而且还对Queue类中的两个自定义类型进行恰当的构造。

如果Stack中的构造函数不是默认构造的话,那将会报错,如下:

class Stack
{
public:
	Stack(int n)	// 非默认构造	error C2280: “Queue::Queue(void)”: 尝试引用已删除的函数
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (_a == nullptr)
		{
			perror("malloc error");
			return;
		}
		_capacity = n;
		_top = 0;
	}
private:
	STDataType* _a;
	int _top;
	int _capacity;
};
...
...

编译器给出的解释: 由于 数据成员“Queue::popst”不具备相应的 默认构造函数 或重载解决不明确,因此已隐式删除函数

所以这个时候,将要采用初始化列表的方法进行对Queue构造。

三、析构函数

析构函数与构造函数功能相反,析构函数不是完成对对象本身的销毁,比如局部对象是存在栈帧的,函数结束栈帧销毁,他就释放了,不需要我们管,C++规定对象在销毁时会自动调用析构函数,完成对象中资源(malloc开辟)的清理释放工作。析构函数的功能类似栈的销毁(Destroy功能),而Date就不需要,因为没有资源需要被释放。

析构函数的特点

  1. 析构函数名时类名前加上字符~。
  2. 无参数无返回。(与构造函数相似,也不需要加void)
  3. 一个类只能有一个析构函数。若未显示定义,系统会自动生成默认的析构函数。
  4. 对象生命周期结束时,系统会自动调用析构函数。(不需要手动Destroy)
  5. 析构顺序,后定义的先析构。(因为成员对象存在函数栈帧中,满足栈帧后入先出特性)
  6. 跟构造函数相似,我们不写编译器自动生成的析构函数对内置类型成员不做处理,自定义成员会调用它的析构函数。
  7. 还需要注意的是我们显示写析构函数,对于自定义类型成员也会调用它的析构,也就是说自定义类型成员无论什么情况都会自动调用析构函数。

示例:(特点7)

#include <iostream>
using namespace std;
typedef int STDataType;
class Stack
{
public:
	Stack(int n = 4)	// 全缺省构造函数为默认构造
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (_a == nullptr)
		{
			perror("malloc error");
			return;
		}
		_capacity = n;
		_top = 0;
	}

	~Stack()
	{
		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}
private:
	STDataType* _a;
	int _top;
	int _capacity;
};

class Queue		// 采用两个栈模拟队列
{
public:
	// 显⽰写析构,也会⾃动调⽤Stack的析构
	~Queue()
	{
		cout << "~Queue()" << endl;
	}
private:
	Stack pushst;
	Stack popst;
};

int main()
{
	Queue q1;
	return 0;
}

调试窗口:

构造完:

在这里插入图片描述

析构完:

在这里插入图片描述

最终输出:
在这里插入图片描述

所以,即使我们显示写析构函数,对于自定义类型成员,仍然自动调用自己的析构。

四、拷贝构造

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

C++规定自定义类型对象进行拷贝行为必须调用拷贝构造。

拷贝构造的特点:

  1. 拷贝构造函数是构造函数的一个重载。

  2. 拷贝构造函数的参数第一个参数必须是类类型对象的引用,使用传值方式编译器直接报错,因为语法逻辑上会引发无穷递归调用。

    因为传值方式,会产生一个临时对象进行拷贝构造(递归),并且这个递归没有跳出窗口,所以为无穷递归调用。

  3. C++规定自定义类型对象进行拷贝行为必须调用拷贝构造,所以这里自定义类型传值传参和传值返回都会调用拷贝构造完成。

  4. 若未显示定义拷贝构造,编译器会自动生成拷贝构造函数。自动生成的拷贝构造函数对内置类型成员变量会完成值拷贝/浅拷贝(一个字节一个字节像memcpy一样的拷贝),对自定义类型成员变量会调用他的拷贝构造。

  5. 像Date这样的类成员变量全是内置类型且没有指向什么资源,编译器自动生成的拷贝构造就可以完成需要的拷贝,所以不需要我们显示实现拷贝构造。像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器自动生成的拷贝构造完成的值拷贝/浅拷贝不符合我们的需求,所以需要我们实现深拷贝(对指向的资源也进行拷贝)。像用两个栈模拟实现的Queue这样的类型内部主要是自定义类型Stack成员,编译器自动生成的拷贝构造会调用Stack的拷贝构造,也不需要我们显示实现Queue的拷贝构造。这里有一个小技巧,如果一个类显示实现了析构并释放资源,那么他就需要显示写拷贝构造,否则就不需要。

  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;
	}
	Date(const Date& d)		// 一般拷贝构造函数传入引用的对象不做修改所以采用const,防止使用不当引发的问题。	// 但是这里不写也没事,因为编译器会自动生成拷贝构造将内置类型浅拷贝。
	{
		_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, 7, 25);
	Date d2(d1);
	d1.Print();		// 2024 7 25
	d2.Print();		// 2024 7 25
	return 0;
}

样例二:用来理解函数栈帧的临时对象拷贝构造。特点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;
	}
	Date(const Date& d)		
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
		cout << "Date(const Date& d)" << endl;
	}
	~Date()
	{
		cout << "~Date()" << endl;
	}
	void Print()
	{
		cout << _year << " " << _month << " " << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

Date func(Date d)	// 产生一个临时对象d来拷贝d1
{
	return d;		// 产生一个临时变量来拷贝d,来向该函数栈帧外传递数据。
}	// 栈帧销毁后,临时变量的生命周期d结束,调用析构函数。

Date func2(const Date& d)	// d为d1的一个别名不需要拷贝构造。
{
	return d;		// 产生一个临时变量来拷贝d,来向该函数栈帧外传递数据。
}
int main()
{
	Date d1;
	func1(d1);	// 返回的临时对象析构
	cout << "------------------------------------" << endl;
	func2(d1);	// 返回的临时对象析构
	cout << "------------------------------------" << endl;
	return 0;
}

输出结果:

在这里插入图片描述

换一种方式:

// ... 同上一样 ...
int main()
{
	Date d1;
	Date d2 = func1(d1);	// 返回的临时对象析构
	cout << "------------------------------------" << endl;
	Date d3 = func2(d1);	// 返回的临时对象析构
	cout << "------------------------------------" << endl;
	return 0;
}

在这里插入图片描述

这里用的是VS2022,编译器将d1构造拷贝给d2和d3的操作优化了,我们可以直接理解临时变量替代了局部对象,并且生命周期与局部对象一致。

示例三:深拷贝 特点5

#include <iostream>
using namespace std;
typedef int STDataType;
class Stack
{
public:
	Stack(int n = 4)	// 全缺省构造函数为默认构造
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (_a == nullptr)
		{
			perror("malloc error");
			return;
		}
		_capacity = n;
		_top = 0;
	}
	Stack(const Stack& st)
	{
		// 需要对_a指向资源创建同样大的资源再拷贝值
		_a = (STDataType*)malloc(sizeof(STDataType) * st._capacity);
		if (_a == nullptr)
		{
			perror("malloc error");
			return;
		}
		memcpy(_a, st._a, sizeof(STDataType) * st._top);
		_top = st._top;
		_capacity = st._capacity;
	}
	void Push(STDataType x)
	{
		if (_top == _capacity)
		{
			int newcapacity = _capacity * 2;
			STDataType* tmp = (STDataType*)realloc(_a, newcapacity * sizeof(STDataType));
			if (tmp == nullptr)
			{
				perror("realloc error");
				return;
			}
			memcpy(tmp, _a, sizeof(STDataType) * _top);
			free(_a);
            _a = tmp;
			_capacity = newcapacity;
			tmp = nullptr;
		}
		_a[_top++] = x;
	}
	~Stack()
	{
		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}
private:
	STDataType* _a;
	int _top;
	int _capacity;
};

class Queue		// 采用两个栈模拟队列
{
public:
	// 编译器默认生成MyQueue的构造函数调用了Stack的构造,完成了两个成员的初始化
	~Queue()
	{
		cout << "~Queue()" << endl;
	}
private:
	Stack pushst;
	Stack popst;
};

int main()
{
	Stack st1;
	st1.Push(1);
	st1.Push(2);
	st1.Push(3);
	st1.Push(4);
	Stack st2(st1);
	st1.Push(5);
	st2.Push(6);
	return 0;
}

调试窗口:

在这里插入图片描述

我们可以看到st2拷贝了st1,并且st1与st2两个对象在完成拷贝之后互不干涉,两对象的成员变量地址均不同。

那么如果我们采用浅拷贝会怎么样?

#include <iostream>
using namespace std;
typedef int STDataType;
class Stack
{
public:
	Stack(int n = 4)	// 全缺省构造函数为默认构造
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (_a == nullptr)
		{
			perror("malloc error");
			return;
		}
		_capacity = n;
		_top = 0;
	}
	// 此处没写拷贝构造,编译器将自动生成浅拷贝(值拷贝)。
	void Push(STDataType x)
	{
		if (_top == _capacity)
		{
			int newcapacity = _capacity * 2;
			STDataType* tmp = (STDataType*)realloc(_a, newcapacity * sizeof(STDataType));
			if (tmp == nullptr)
			{
				perror("realloc error");
				return;
			}
			memcpy(tmp, _a, sizeof(STDataType) * _top);
            free(_a);
			_a = tmp;
			_capacity = newcapacity;
			tmp = nullptr;
		}
		_a[_top++] = x;
	}
	~Stack()
	{
		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}
private:
	STDataType* _a;
	int _top;
	int _capacity;
};

int main()
{
	Stack st1;
	st1.Push(1);
	st1.Push(2);
	st1.Push(3);
	st1.Push(4);
	Stack st2(st1);
	return 0;
}

在这里插入图片描述

我们通过调试可以看到两个对象的成员变量_a的地址是一样的,这将会导致很多问题比如:对st1进行修改,st2被连带修改;析构st2后,_a的空间已被释放,析构st1,再次释放将报错;并且如果_a进行扩容也会有很多问题。所以当值拷贝无法满足我们的时候,我们必须得自己编写将指向的资源也进行拷贝。特点5。

示例四:自定义类型自动调用其拷贝构造。 特点4

#include <iostream>
using namespace std;
typedef int STDataType;
class Stack
{
public:
	Stack(int n = 4)	// 全缺省构造函数为默认构造
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (_a == nullptr)
		{
			perror("malloc error");
			return;
		}
		_capacity = n;
		_top = 0;
	}
	Stack(const Stack& st)
	{
		// 需要对_a指向资源创建同样大的资源再拷贝值
		_a = (STDataType*)malloc(sizeof(STDataType) * st._capacity);
		if (_a == nullptr)
		{
			perror("malloc error");
			return;
		}
		memcpy(_a, st._a, sizeof(STDataType) * st._top);
		_top = st._top;
		_capacity = st._capacity;
	}

	void Push(STDataType x)
	{
		if (_top == _capacity)
		{
			int newcapacity = _capacity * 2;
			STDataType* tmp = (STDataType*)realloc(_a, newcapacity * sizeof(STDataType));
			if (tmp == nullptr)
			{
				perror("realloc error");
				return;
			}
			memcpy(tmp, _a, sizeof(STDataType) * _top);
			free(_a);
			_a = tmp;
			_capacity = newcapacity;
			tmp = nullptr;
		}
		_a[_top++] = x;
	}
	~Stack()
	{
		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}
private:
	STDataType* _a;
	int _top;
	int _capacity;
};

class Queue		// 采用两个栈模拟队列
{
public:
	// 编译器默认生成MyQueue的构造函数调用了Stack的构造,完成了两个成员的初始化
	~Queue()
	{
		cout << "~Queue()" << endl;
	}
private:
	Stack pushst;
	Stack popst;
};

int main()
{
	Queue q1;
	Queue q2(q1);
	return 0;
}

在这里插入图片描述

我们可以看到两个对象完成的拷贝,两个对象的_a地址不同,很明显是调用了自身的拷贝构造(深拷贝)。

五、赋值运算符重载

(一)、运算符重载

  • 当运算符被用于类类型的对象时,C++语言允许我们通过运算符重载的形式指定新的含义。C++规定类类型对象使用运算符时,必须转换成调用对应运算符重载,若没有对应的运算符重载,则会变异报错

  • 运算符重载是具有特名字的函数,他的名字是有operator和后面要定义的运算符共同构成。和其他函数一样,他也具有其返回类型和参数列表以及函数体。

  • 重载运算符函数的参数个数和该运算符作用的运算对象数量一样多。一元运算符有一个参数,二元运算符有两个参数,二元运算符的左侧运算对象传给第一个参数,右侧运算对象传给第二个参数。

  • 如果⼀个重载运算符函数是成员函数,则它的第⼀个运算对象默认传给隐式的this指针,因此运算符重载作为成员函数时,参数比运算对象少⼀个。

  • 运算符重载以后,其优先级和结合性与对应的内置类型运算符保持⼀致。

  • 不能通过连接语法中没有的符号来创建新的操作符:⽐如operator@。

  • .* :: sizeof ?: . 注意以上5个运算符不能重载。

    // .*运算符的用法, 回调成员函数的时候使用(很少用到)
    #include <iostream>
    using namespace std;
    class A
    {
    public:
    	void func()
    	{
    		cout << "func()" << endl;
    	}
    };
    
    typedef void(A::*PF)();		// 成员函数指针类型
    int main()
    {
    	//void(A::*pf)() = nullptr;
    	PF pf = nullptr;
    	// C++规定成员函数要加&才能取到函数指针,而正常函数,函数名也是函数地址。
    	pf = &A::func;
    	A aa;
    	(aa.*pf)();		// .*运算符 对象aa目的是穿给成员函数func中隐含的this指针。
    	return 0;
    }
    
  • 重载操作符⾄少有⼀个类类型参数,不能通过运算符重载改变内置类型对象的含义,如int operator+(int x, int y)

  • ⼀个类需要重载哪些运算符,是看哪些运算符重载后有意义,⽐如Date类重载operator-就有意义,但是重载operator+就没有意义。

  • 重载++运算符时,有前置++和后置++,运算符重载函数名都是operator++,⽆法很好的区分。C++规定,后置++重载时,增加⼀个int形参,跟前置++构成函数重载,⽅便区分。

  • 重载<<和>>时,需要重载为全局函数,因为重载为成员函数,this指针默认抢占了第⼀个形参位置,第⼀个形参位置是左侧运算对象,调⽤时就变成了 对象<<cout,不符合使⽤习惯和可读性。重载为全局函数把ostream/istream放到第⼀个形参位置就可以了,第⼆个形参位置当类类型对象。

示例一:

#include <iostream>
using namespace std;
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	
	bool operator==(const Date& d)
	{
		cout << "bool operator==(const Date& d)" << endl;
		return _year == d._year
			&& _month == d._month
			&& _day == d._day;
	}

	int _year;
	int _month;
	int _day;
};

bool operator==(const Date& d1, const Date& d2)	// 一般不采用次方法,因为成员变量一般定义为私有
{
	cout << "bool operator==(const Date& d1, const Date& d2)" << endl;
	return d1._year == d2._year
		&& d1._month == d2._month
		&& d1._day == d2._day;
}
int main()
{
	Date d1(2024, 7, 27), d2(2024, 7, 28);

	// 运算符重载可以显示调用
	operator==(d1, d2);
	
	// 调用成员函数优先级更高
	d1 == d2;	// 编译器会自动转换为d1.operator==(d2)
	
	d1.operator==(d2);	
	return 0;
}

在这里插入图片描述

上面方法将运算符重载为全局,一般我们不采用,因为会面临对象访问私有成员变量的问题

有几种方法可以解决:

  1. 成员放公有 (不推荐)
  2. Date提供getxxx函数 (Java语言经常使用)
  3. 友元函数
  4. 重载为成员函数 (最为常用)

(二)、赋值运算符重载

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

Date d1;
// 拷贝构造
Date d2(d1);	
Date d3 = d1;
// 赋值重载拷贝
Date d4;
d4 = d1;
赋值运算符重载的特点:
  1. 赋值运算符重载是⼀个运算符重载,规定必须重载为成员函数。赋值运算重载的参数建议写成 const 当前类类型引用,否则会传值传参会有拷贝。
  2. 有返回值,且建议写成当前类类型引用,引用返回可以提高效率,有返回值目的是为了⽀持连续赋值场景。
  3. 没有显式实现时,编译器会自动生成⼀个默认赋值运算符重载,默认赋值运算符重载行为跟默认拷贝构造函数类似,对内置类型成员变量会完成值拷贝/浅拷贝(⼀个字节⼀个字节像memcpy的拷贝),对自定义类型成员变量会调用他的赋值重载。
  4. 像Date这样的类成员变量全是内置类型且没有指向什么资源,编译器自动生成的赋值运算符重载就可以完成需要的拷贝,所以不需要我们显示实现赋值运算符重载。像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器自动生成的赋值运算符重载完成的值拷贝/浅拷贝不符合我们的需求,所以需要我们自己实现深拷贝(对指向的资源也进行拷贝)。像用两个栈模拟队列的Queue这样的类型内部主要是自定义类型Stack成员,编译器⾃动生成的赋值运算符重载会调用Stack的赋值运算符重载,也不需要我们显示实现MyQueue的赋值运算符重载。这⾥还有⼀个小技巧,如果⼀个类显示实现了析构并释放资源,那么他就需要显⽰写赋值运算符重载,否则就不需要。(总结:与拷贝构造一致)

示例一:

#include <iostream>
using namespace std;
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void operator=(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, 7, 28);
	Date d2;
	d2 = d1;
	d1.Print();
	d2.Print();
	return 0;
}

示例二:将上面的赋值运算重载改成下面就能实现连续的赋值

Date& operator=(const Date& d)	// 引用返回,省去了成员函数返回时不必要的拷贝构造,提高效率
{
    _year = d._year;
    _month = d._month;
    _day = d._day;
    return *this;
}
int main()
{
    Date d1(2024, 7, 28);
    Date d2, d3;
    d3 = d2 = d1;	// 连续赋值
	return 0;
}

自主实现一个日期类

// Date.h
#pragma once
#include <iostream>
#include <assert.h>

using namespace std;

class Date
{
	// 友元函数
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);
public:
	Date(int year = 1900, int month = 1, int day = 1);
	void Print() const;

	bool CheckDate() const;

	// 定义到类中的成员函数,默认是inline
	int GetMonthDay(int year, int month) const
	{
		static int monthDayArray[13] = { -1, 31, 28, 31, 30, 31, 30, 31,
			31, 30, 31, 30, 31 };
		if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
			return 29;
		return monthDayArray[month];
	}
	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;

	Date operator+(int day) const;
	Date& operator+=(int day);
	Date operator-(int day) const;
	Date& operator-=(int day);
	
	// ++d1;	// 一般情况下最好用前置++,因为对象拷贝次数比较少,0次
	// d1.operator++();
	Date& operator++();

	// d1++;	// 两次拷贝构造
	// d1.operator++(0);
	Date operator++(int);

	// --d1;
	Date& operator--();
	// d1--;
	Date operator--(int);

	int operator-(const Date& d) const;

	void operator<<(ostream& out);
private:
	int _year;
	int _month;
	int _day;
};

// 流对象不支持拷贝所以一定得用引用避免拷贝
ostream& operator<<(ostream& out, const Date& d);	
istream& operator>>(istream& in, Date& d);
// Date.cpp
#include "Date.h"

bool Date::CheckDate() const
{
	if (_month < 1 || _month > 12 || _day < 1 || _day > GetMonthDay(_year, _month))
	{
		return false;
	}
	return true;
}
Date::Date(int year, int month, int day)
{
	_year = year;
	_month = month;
	_day = day;
	if (!CheckDate())	// this->CheckDate()
	{
		cout << "非法日期" << endl;
		Print();
	}
}

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

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

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

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

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

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

bool Date::operator!=(const Date& d) const
{
	return !(*this == d);
}

Date& Date::operator+=(int day)
{
	_day += day;
	while (_day > GetMonthDay(_year, _month))
	{
		_day -= GetMonthDay(_year, _month);
		_month++;
		if (_month > 12)
		{
			_year++;
			_month = 1;
		}
	}
	return *this;
}

Date Date::operator+(int day) const
{
	Date tmp = *this;
	tmp += day;

	/*tmp._day += day;
	while (tmp._day > GetMonthDay(tmp._year, tmp._month))
	{
		tmp._day -= GetMonthDay(tmp._year, tmp._month);
		tmp._month++;
		if (tmp._month > 12)
		{
			tmp._year++;
			tmp._month = 1;
		}
	}*/
	return tmp;
}

Date& Date::operator-=(int day)
{
	if (day < 0)
	{
		return *this += -day;
	}
	_day -= day;
	while (_day <= 0)
	{
		_month--;
		if (_month == 0)
		{
			_year--;
			_month = 12;
		}
		_day += GetMonthDay(_year, _month);
	}
	return *this;
}

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

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

// d1--
Date Date::operator--(int)
{
	Date tmp;
	*this -= 1;
	return tmp;
}
int Date::operator-(const Date& d) const
{
	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 flag * n;
}

void Date::operator<<(ostream& out)
{
	out << _year << "年" << _month << "月" << _day << "日" << endl;
}

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

istream& operator>>(istream& in, Date& d)
{
	while (1)
	{
		cout << "请依次输入年月日:>";
		in >> d._year >> d._month >> d._day;

		if (!d.CheckDate())
		{
			cout << "输入日期非法:";
			d.Print();
			cout << "请重新输入!!!" << endl;
		}
		else
		{
			break;
		}
	}
	return in;
}
// Test.cpp
#include "Date.h"

void Test1()
{
	Date d1(2024, 7, 31);
	Date d2 = d1 + 100;
	d1.Print();
	d2.Print();

	d1 += 100;
	d1.Print();
}

void Test2()
{
	Date d1(2024, 7, 31);
	Date d2 = d1 - 1000;
	d1.Print();
	d2.Print();

	d1 -= 1000;
	d1.Print();
}

void Test3()
{
	Date d1(2024, 7, 31);
	Date d2 = d1;
	Date d3 = d1++;
	Date d4 = ++d2;
	d1.Print();
	d3.Print();
	d2.Print();
	d4.Print();
}

void Test4()
{
	Date d1(2024, 7, 31);
	Date d2(2024, 8, 31);
	int count = d1 - d2;
	cout << count << endl;
}

void Test5()
{
	Date d1;
	Date d2;
	cin >> d1 >> d2;
	cout << d1 << d2;
}
int main()
{
	//Test1();
	//Test2();
	//Test3();
	//Test4();
	Test5();
	return 0;
}

六、取地址运算符重载

1.const成员函数

  • 将const修饰的成员函数称之为const成员函数,const修饰成员函数放到成员函数参数列表的后面。
  • const实际修饰该成员变量隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。const修饰Date类的Print成员函数,Print隐含的this指针由Date* const this变成const Date* const this
  • 当我们要对一个const的对象使用成员函数,为了防止拷贝时权限放大的问题,所以成员函数在不对类的任何成员进行修改的时候尽量使用const成员函数。
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)
   	void Print() const
    {
        cout << _year << "-" << _month << "-" << _day << endl;
    }
private:
    int _year;
    int _month;
    int _day;
};

2.取地址运算符重载

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

class Date
{
public:
    Date* operator&()
    {
		return this;
    }
    const Date* operator&() const
    {
        return this;
    }
private:
    int _year;
    int _month;
    int _day;
};
  • 18
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值