类和对象(中)

类和对象(中)

类的默认成员函数

我们不写,编译器会自动生成的函数,即不显式实现

一共有6个默认成员函数,我们重点介绍前四个:构造、析构、拷贝构造、赋值重载

构造函数

在对象实例化的时候,初始化对象,只是名字叫构造而已,不是创造对象

构造函数的特点:

  • 函数名与类名相同
  • 无返回值
  • 对象实例化时系统会自动调用对应的构造函数
  • 构造函数可以重载(可以定义多种初始化的方式)
class Date
{
public:
	//无参构造函数:
	Date()
	{
		_year = 1;
		_month = 1;
		_day = 1;
	}
	//带参构造函数:
	//Date(int y, int m, int d)
	//{
	//	_year = y;
	//	_month = m;
	//	_day = d;
	//}
	//全缺省构造函数:
	Date(int y = 1, int m = 1, int d = 1)
	{
		_year = y;
		_month = m;
		_day = d;

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

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

int main()
{
	//无参调用
//	Date d1;
//  Date d1();//无参构造不要这样写,会和函数混淆
//	d1.Print();

	//带参调用
	/*Date d2(2024, 7, 12);
	d2.Print();*/
	
	//全缺省调用,它存在,带参和无参调用就不能存在,因为区分不开,会有歧义,但其实,有了全缺省,也不需要那俩了
	Date d3(2024);
	d3.Print();
	
	return 0;

}
  • 如果类中没有显示定义构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显示定义编译器将不再生成
  • 编译器默认生成的构造,对内置类型成员变量的初始化没有要求,也就是说是否初始化是不确定的,取决于编译器,对于自定义类型成员变量,要求调用这个成员变量的默认构造函数初始化。如果这个成员变量,没有默认构造函数,那么就会报错,我们要初始化这个成员变量,需要使用初始化列表才能解决。

说明:C++把类型分为内置类型(基本类型)和自定义类型,内置类型就是语言提供的原生数据类型,比如:int/char/double/指针等,自定义类型就是我们使用class/struct等关键字自己定义的类型。

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;
	}
private:
	STDataType* _a;
	size_t _capacity;
	size_t _top;
};

// 两个Stack实现队列
class MyQueue
{
public:
	//这里就不用显式实现MyQueue的构造函数,因为Stack是自定义类型,会调用它的默认构造
private:
	Stack pushst;
	Stack popst;
};

int main()
{
	MyQueue mq;

	return 0;
}

但是大多数情况,构造函数都需要我们自己去实现。

析构函数

析构函数与构造函数功能相反,析构函数不是完成对对象本⾝的销毁,⽐如局部对象是存在栈帧的,函数结束栈帧销毁,他就释放了,所以空间本身的销毁不需要我们管,析构函数完成的是对象中的资源清理释放⼯作。析构函数的功能类⽐我们之前Stack实现的Destroy功能。

析构函数的特点:

  • 析构函数名是在类名前加上字符 ~
  • 无参数无返回值(和构造类似)
  • 一个类只能由一个析构函数,若为显示定义,系统会自动生成默认的析构函数
  • 对象生命周期结束时,系统会自动调用析构函数
  • 跟构造函数类似,我们不写编译器⾃动⽣成的析构函数对内置类型成员不做处理,⾃定类型成员会调⽤他的析构函数,也就是说,有资源申请的类,需要自己写析构
  • 当存在多个对象的时候,后定义的先析构
typedef int STDataType;
class Stack
{
public:
	void Init(int n = 4)
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (nullptr == _a)
		{
			perror("malloc fail\n");
			return;
		}
		_capacity = n;
		_top = 0;
	}

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

如果有多个对象,后定义的先析构(类似于栈帧,后进先出)

  • 我们显⽰写析构函数,对于⾃定义类型成员也会调⽤他的析构,也就是说自定义类型成员⽆论什么情况都会自动调⽤析构函数
//那如果我犯贱,把本来编译器自己会调的函数换成自己的,但是我又什么都不干,这样的代码会寄吗?
class MyQueue
{
public:
	~MyQueue()
	{
		cout << "~MyQueue()" << endl;
	}
private:
	Stack pushst;
	Stack popst;
};
//运行成功

对于自定义成员,你写不写自己的析构函数,它都会调用自己的析构函数,所以这段代码可以正常运行,但是如果你连Stack的析构函数也不写,那就会报错了。(你自己要作,也没办法(doge )

  • 如果类中没有申请资源时,析构函数可以不写,直接使⽤编译器⽣成的默认析构函数,如Date;如果默认⽣成的析构就可以⽤,也就不需要显⽰写析构,如MyQueue;但是有资源申请时,⼀定要⾃⼰写析构,否则会造成资源泄漏,如Stack

拷贝构造函数

**一个构造函数的第一个参数是自身类类型的引用,且任何额外的参数都有缺省值,**则此构造函数又叫拷贝构造函数,它是一种特殊的构造函数

拷贝构造函数的特点:

  • 拷贝构造函数是构造函数的一个重载
  • 拷贝构造函数的第一个参数必须是类类型对象的引用,使用传值方式编译器将直接报错。
class Date
{
public:
	Date(int y, int m, int d)
	{
		_year = y;
		_month = m;
		_day = d;
	}
	//拷贝构造
	Date(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._year;
	}
	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

void Func1(Date d)
{
	cout << &d << endl;
	d.Print();
}

int main()
{
	Date d1(2024, 7, 13);
	d1.Print();

	//C++规定,传值传参要调用拷贝构造:
	Func1(d1);
	return 0;
}
  • C++规定,自定义类型对象进行拷贝必须调用拷贝构造,所以自定义类型传值传参和传值返回都会调用拷贝构造
  • 若未显式定义拷⻉构造,编译器会⽣成⾃动⽣成拷⻉构造函数。⾃动⽣成的拷⻉构造对内置类型成员变量会完成值拷⻉/浅拷⻉(⼀个字节⼀个字节的拷⻉),对⾃定义类型成员变量会调⽤他的拷⻉构造。这就是拷贝构造函数和构造函数不同的一点,内置类型和自定义类型它都会管

所以我们要实现自己的深拷贝:

Stack(const Stack& st)
{
	// 需要对_a指向资源创建同样⼤的资源再拷⻉值
	_a = (STDataType*)malloc(sizeof(STDataType) * st._capacity);
	if (nullptr == _a)
	{
		perror("malloc fail\n");
	}
	_top = st._top;
	_capacity = st._capacity;
}
  • 像Date这样的类成员变量全是内置类型且没有指向什么资源,编译器⾃动⽣成的拷⻉构造就可以完成需要的拷⻉,所以不需要我们显⽰实现拷⻉构造。

  • 传值返回会产⽣⼀个临时对象调⽤拷⻉构造,传值引⽤返回,返回的是返回对象的别名(引⽤),没有产⽣拷⻉。但是如果返回对象是⼀个当前函数局部域的局部对象,函数结束就销毁了,那么使⽤引⽤返回是有问题的,这时的引⽤相当于⼀个野引⽤,类似⼀个野指针⼀样。传引⽤返回可以减少拷⻉,但是⼀定要确保返回对象,在当前函数结束后还在,才能⽤引⽤返回

那什么情况下这种局部返回的才可以用引用呢?很简单,把它放到全局不就行了?

Stack& func2()
{
	static Stack st;//把st放在全局,出了func2它还在,这样我们可以减少拷贝
	return st;
}

int main()
{
	Stack ret = func2();
	return 0;
}

拷贝构造除了写成括号的形式,还可以用=来写

Stack st1;
st1.Push(1);
st1.Push(2);

Stack st2(st1);
Stack st3 = st1;//这两种写法都可以,都是拷贝构造

运算符重载

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

比如我想实现日期类比较大小,C++肯定没有这样的比较符号,我们就可以重载

  • 当运算符被⽤于类类型的对象时,C++语⾔允许我们通过运算符重载的形式指定新的含义。C++规

    定类类型对象使⽤运算符时,必须转换成调⽤对应运算符重载,若没有对应的运算符重载,则会编

    译报错。

  • 运算符重载是具有特殊名字的函数,他的名字是由operator和后面要定义的运算符共同构成。和其他

    函数⼀样,它也具有其返回类型和参数列表以及函数体。

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

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

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

  • 不能用语法中没有的符号,创建新的操作符:⽐如operator@,这就没有这个符号。

  • ::(域作用限定符)、sizeof、?:(三目运算符)、. 、.*(是. *,不是 * , *可以重载) 这5个运算符不能重载

  • 重载操作符⾄少有⼀个类类型参数,不能通过运算符重载改变内置类型对象的含义,如: int operator+(int x, int y),本来int x和int y的加法就是x + y ,你不能说重载里面实现的是x - y,这就不行

  • ⼀个类需要重载哪些运算符,是看哪些运算符重载后有意义,⽐如Date类重载operator-就有意义,但是重operator+就没有意义(日期+日期确实没什么意思)

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

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

最常见的重载就是重载成全局的,但是重载为全局的会面临对象访问私有成员变量的问题,解决办法有以下几种:

  • 成员放公有(最粗暴,最挫的方法)
  • 类中提供GetXXX()函数 (JAVA喜欢用这种方式)
  • 友元函数
  • 重载为成员函数(但是有些符号不能重载为成员函数)---->推荐这种方式

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

如果全局的和成员的同时存在,会先调用哪一个?

优先调用成员的(但是一般你没病的话就不会两个都写)

运算符重载和函数重载没有关系。但是两个运算符重载的函数又构成函数重载,比如:

Date operator-(int day);
int operator-(const Date& d);
//这两个运算符重载就构成了 operator-这个函数的重载

赋值运算符重载

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

Date d1(2024, 1, 3);
Date d2(2024, 7, 13);
//复制重载拷贝:
d1 = d2;//d1,d2都是已经存在的对象

//拷贝构造:
Date d3(d2);
Date d4 = d2;//这俩都是拷贝构造

赋值运算符重载的特点:

  • 规定必须重载为成员函数,赋值运算符重载建议写成const当前类类型引用(写成传值传参也行,只是建议),否则会传值传参会有拷贝
void operator=(const Date& d)//这样写可以减少一次拷贝,你非要写传值传参也随你便
{
	_year = d._year;
	_month = d._month;
	_day = d._day;
}
  • 有返回值,且建议写成当前类类型引用,引用返回可以提高效率,有返回值目的是为了支持连续赋值场景
//部分代码:
Date& operator=(const Date& d)//这样写可以减少一次拷贝,你非要写传值传参也随你便
{
	_year = d._year;
	_month = d._month;
	_day = d._day;
    return *this;//传值返回会生成一个拷贝,浪费,所以我们最好使用引用返回
}

int main()
{
    Date d1, d3, d4;
    d4 = d3 = d1;//d3 = d1,返回值是d3,d4 = d3,返回值是d4
}
  • 没有显式实现时,编译器会⾃动⽣成⼀个默认赋值运算符重载,默认赋值运算符重载行为跟默认拷贝构造函数类似,对内置类型成员变量会完成值拷贝/浅拷⻉(⼀个字节⼀个字节的拷⻉),对⾃定义类型成员变量会调⽤他的赋值重载

取地址运算符重载

取地址运算符重载分为普通取地址运算符重载和const取地址运算符重载,一般这两个函数编译器自动生成的就够我们使用了,不需要显式实现。

流插入流提取重载

这里C++兼容C,printf不会刷新缓冲区,但是cout会,假如前一句是printf,下一句是cout,那么cout会先刷新printf的缓冲区,再刷新自己的缓冲区,所以在需要大量I/O的编程题中,使用cin/cout可能效率就不够,所以可以加上下面三段代码:

ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);

这样可以不用刷新C语言的,可以提高效率

istream& operator>>(istream& in, Date& d)
{
	cout << "请输入年月日:>" << endl;
	in >> d._year >> d._month >> d._day;
	
	return in;
}

cout和cin是绑定的,也就是在cin进行I/O操作之前,会刷新cout的缓冲区,所以这里面使用cout不会影响的

日期类实现

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

class Date
{
public:
	friend istream& operator >> (istream& in, Date& d);
	friend ostream& operator << (ostream& out, const Date& d);
	Date(int year = 1999, 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;
	}

	int GetMonthDay(int year, int month)
	{
		static int day[] = { 0,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 day[month];
	}

	bool CheckMonthDay(int year, int month, int day)
	{
		if (month > 0
			&& month < 13
			&& day > 0
			&& day <= GetMonthDay(year, month))
			return true;
		return false;
	}

	//析构函数
	~Date()
	{
		;
	}

	//赋值运算符重载:
	Date& operator = (const Date& d);

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

	// 日期+天数
	Date operator+(int day);

	// 日期-天数
	Date operator-(int day);

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

	// 前置++
	Date& operator++();

	// 后置++
	Date operator++(int);

	// 后置--
	Date operator--(int);

	// 前置--
	Date& operator--();

	// >运算符重载
	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;

	// 日期差:
	int operator - (const Date& d) const;


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

istream& operator >> (istream& in, Date& d);
ostream& operator << (ostream& out, const Date& d);

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

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

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

//赋值运算符重载:
Date& Date::operator = (const Date& d)
{
	_year = d._year;
	_month = d._month;
	_day = d._day;
	return *this;
}

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

// 日期+天数
Date Date::operator+(int day)
{
	Date tmp = *this;
	tmp += day;
	return tmp;
}

// 日期-天数
Date Date::operator-(int day)
{
	Date tmp = *this;
	tmp -= day;
	return tmp;
}

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

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

// 后置++
Date Date::operator++(int)
{
	Date tmp = *this;
	++*this;
	return tmp;
}

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

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

// 日期差:
int Date::operator - (const Date& d) const
{
	Date max = *this;
	Date min = d;
	int flag = 1;
	if (max < min)
	{
		max = d;
		min = *this;
		flag = -1;
	}

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

	return n * flag;
}

// >运算符重载
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;
	}
	else
	{
		return false;
	}
}

// ==运算符重载
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 || *this > d;
}

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

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

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

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

void test1()
{
	Date d1(2024, 7, 31);
	Date d2(2023, 6, 5);

	Date d3 = d2;
	cout << d1;
	cout << d2;
	cout << d3;
}

void test2()
{
	Date d;
	cin >> d;
	cout << d;
}

void test3()
{
	Date d1;
	Date d2;
	cin >> d1 >> d2;
	cout << (d1 - d2) << endl;
}

void test4()
{
	Date d(2024, 6, 24);
	Date tmp = d + 1000;
	cout << tmp;
	d += -1000;
	cout << d;
}

void test5()
{
	Date d1(2024, 7, 2);
	Date d2(2025, 8, 1);
	Date d3 = d2;
	Date d4(2023, 6, 1);

	cout << (d1 > d2) << endl;
	cout << (d1 >= d2) << endl;
	cout << (d1 <= d2) << endl;
	cout << (d2 == d3) << endl;
	cout << (d3 != d2) << endl;
	cout << (d4 < d2) << endl;
	cout << (d4 <= d2) << endl;
}

int main()
{
	test5();
	return 0;
}




;
}

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

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

void test1()
{
	Date d1(2024, 7, 31);
	Date d2(2023, 6, 5);

	Date d3 = d2;
	cout << d1;
	cout << d2;
	cout << d3;
}

void test2()
{
	Date d;
	cin >> d;
	cout << d;
}

void test3()
{
	Date d1;
	Date d2;
	cin >> d1 >> d2;
	cout << (d1 - d2) << endl;
}

void test4()
{
	Date d(2024, 6, 24);
	Date tmp = d + 1000;
	cout << tmp;
	d += -1000;
	cout << d;
}

void test5()
{
	Date d1(2024, 7, 2);
	Date d2(2025, 8, 1);
	Date d3 = d2;
	Date d4(2023, 6, 1);

	cout << (d1 > d2) << endl;
	cout << (d1 >= d2) << endl;
	cout << (d1 <= d2) << endl;
	cout << (d2 == d3) << endl;
	cout << (d3 != d2) << endl;
	cout << (d4 < d2) << endl;
	cout << (d4 <= d2) << endl;
}

int main()
{
	//test1();
	//test2();
	//test3();
	//test4();
	test5();
	return 0;
}
  • 16
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值