C++学习笔记(五)---【类与对象】(中)

【知识预告】

  1. 类的6个默认成员函数
  2. 构造函数
  3. 析构函数
  4. 拷贝构造函数
  5. 赋值运算符重载
  6. const成员函数
  7. 取地址及const取地址操作符

1 类的6个默认成员函数

如果一个类中什么成员都没有,简称为空类。

空类中真的什么都没有吗?并不是,任何类在什么都不写时,编译器会自动生成以下6个默认成员函数。

默认成员函数:用户没有显式实现,编译器会生成的成员函数称为默认成员函数。

class Date {};

初始化清理:

  1. 构造函数主要完成初始化工作
  2. 析构函数主要完成清理工作

拷贝复制:

  1. 拷贝构造是使用同类对象初始化创建对象
  2. 赋值重载主要是把一个对象赋值给另一个对象

取地址重载:

  1. 主要是普通对象const对象取地址,这两个很少会自己实现

2 构造函数

对于以下Date类:

class Date
{
public:
	void Init(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 d;
	d.Print();  // 忘记初始化了,就会打印随机值
	return 0;
}

对于Date类,可以通过 Init 公有方法给对象设置日期,但如果每次创建对象时都调用该方法设置信息,未免有点麻烦,那能否在对象创建时,就将信息设置进去呢?

2.1 概念

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

2.2 特性

构造函数是特殊的成员函数,需要注意的是,构造函数虽然名称叫构造,但是构造函数的主要任务并不是开空间创建对象,而是初始化对象

其特征如下:

  1. 函数名与类名相同。
  2. 无返回值。(不需要写void)
  3. 对象实例化时编译器自动调用对应的构造函数。
  4. 构造函数可以重载。(可以写多个构造函数,提供多种初始化方式)
  5. 如果类中没有显式定义构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定义编译器将不再生成。
  6. C++把类型分成内置类型(基本类型)和自定义类型。内置类型就是语言提供的数据类型,如:int/char…,自定义类型就是使用class/struct/union等自己定义的类型,内置类型的成员不会处理,自定义类型的成员才会处理(去调用它自己的默认构造)。
class A
{
public:
	A(int a = 1)
	{
		cout << "A(int a)" << endl;
		_a = a;
	}

private:
	int _a;
};

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

	//~Date()
	//{
	//	cout << "~Date()" << endl;
	//}

private:
	// 内置类型
	int _year = 1;   // 声明给的缺省值
	int _month = 1;
	int _day = 1;

	// 自定义类型(调用它自己的默认构造)
	A _aa;
};

int main()
{
	Date d1;   // 输出:A(int a)
	return 0;
}
  1. 无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个。注意:无参构造函数、全缺省构造函数、我们没写编译器默认生成的构造函数,都可以认为是默认构造函数。
class Date
{
public:
	// 构造函数
	//Date()
	//{
	//	cout << "Date()" << endl;
	//	_year = 1;
	//	_month = 1;
	//	_day = 1;
	//}

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

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

	void Init(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;
	d1.Print();

	Date d2(2024, 9, 25);
	d2.Print();

	Date d3(2024);
	d3.Print();

	Date d4(2024, 9);
	d4.Print();

	return 0;
}
class Stack
{
public:
	//Stack()
	//{
	//	a = nullptr;
	//	top = capacity = 0;
	//}

	Stack(size_t n = 4)
	{
		if (n == 0)
		{
			a = nullptr;
			top = capacity = 0;
		}
		else
		{
			a = (int*)malloc(sizeof(int) * n);
			if (a == nullptr)
			{
				perror("malloc fail");
				exit(-1);
			}
			top = 0;
			capacity = n;
		}
	}

	// 成员函数
	void Init()
	{
		a = nullptr;
		top = capacity = 0;
	}

	void Push(int x)
	{
		if (top == capacity)
		{
			cout << capacity << "扩容" << endl;
			int newcapacity = capacity == 0 ? 4 : capacity * 2;
			int* tmp = (int*)realloc(a, sizeof(int) * newcapacity);
			if (tmp == nullptr)
			{
				perror("realloc fail");
				exit(-1);
			}
			if (tmp == a)
			{
				cout << capacity << "原地扩容" << endl;
			}
			else
			{
				cout << capacity << "异地扩容" << endl;

			}
			a = tmp;

			capacity = newcapacity;
		}
		a[top++] = x;
	}

	int Top()
	{
		return a[top - 1];
	}

	void Pop()
	{
		assert(top > 0);
		--top;
	}

	void Destroy()
	{
		free(a);
		a = nullptr;
		top = capacity = 0;
	}

	bool Empty()
	{
		return top == 0;
	}

private:
	// 成员变量,一般都是私有
	int* a;
	int top;
	int capacity;
};

int main()
{
	Stack st1;
	st1.Init();
	st1.Push(1);
	st1.Push(2);
	st1.Push(3);
	st1.Push(4);

	while (!st1.Empty())
	{
		cout << st1.Top() << " ";
		st1.Pop();
	}
	cout << endl;

	st1.Destroy();

	// 扩容代价很大,初始化时,malloc一次扩到位
	Stack st2(1000);
	//Stack st2;

	for (int i = 0; i < 1000; i++)
	{
		st2.Push(i);
	}

	while (!st2.Empty())
	{
		cout << st2.Top() << " ";
		st2.Pop();
	}
	cout << endl;

	st2.Destroy();
	return 0;
}

总结:一般情况都需要我们自己写构造函数,决定初始化方式,除非成员变量全是自定义类型,可以考虑不写构造函数。构造函数最厉害的不是自动生成,而是自动调用。

3 析构函数

3.1 概念

析构函数:与构造函数功能相反,析构函数不是完成对对象本身的销毁,局部对象销毁工作是由编译器完成的。而对象在销毁时会自动调用析构函数,完成对象中资源的清理工作。

3.2 特性

  1. 析构函数名是在类名前加上字符 ~。
  2. 无参数无返回值类型。
  3. 一个类只能有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。注意:析构函数不能重载
    1. 内置类型成员不做处理
    2. 自定义类型成员会调用这个成员的析构函数
  4. 对象生命周期结束时,C++编译系统自动调用析构函数
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		cout << "默认构造函数" << endl;
		_year = year;
		_month = month;
		_day = day;
	}

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

	~Date()
	{
		cout << "~Date()" << endl;
	}

private:
	int _year = 1;   // 声明给的缺省值
	int _month = 1;
	int _day = 1;
};

int main()
{
	Date d1;
	return 0;
}
// 日期类,不需要写析构函数(d1出了作用域自动销毁)
// 析构函数也是自动调用
class Stack
{
public:
	Stack(size_t n = 4)
	{
		cout << "Stack(size_t n = 4)" << endl;
		if (n == 0)
		{
			a = nullptr;
			top = capacity = 0;
		}
		else
		{
			a = (int*)malloc(sizeof(int) * n);
			if (a == nullptr)
			{
				perror("realloc fail");
				exit(-1);
			}
			top = 0;
			capacity = n;
		}
	}

	~Stack()
	{
		cout << "~Stack()" << endl;
		free(a);
		a = nullptr;
		top = capacity = 0;
	}

	void Push(int x)
	{
		if (top == capacity)
		{
			cout << capacity << "扩容" << endl;
			int newcapacity = capacity == 0 ? 4 : capacity * 2;
			int* tmp = (int*)realloc(a, sizeof(int) * newcapacity);
			if (tmp == nullptr)
			{
				perror("realloc fail");
				exit(-1);
			}
			if (tmp == a)
			{
				cout << capacity << "原地扩容" << endl;
			}
			else
			{
				cout << capacity << "异地扩容" << endl;

			}
			a = tmp;
			capacity = newcapacity;
		}
		a[top++] = x;
	}

	int Top()
	{
		return a[top - 1];
	}

	void Pop()
	{
		assert(top > 0);
		--top;
	}

	void Destroy()
	{
		free(a);
		a = nullptr;
		top = capacity = 0;
	}

	bool Empty()
	{
		return top == 0;
	}

private:
	int* a;
	int top;
	int capacity;
};

int main()
{
	// 后定义的先析构
	Stack st1;
	Stack st2;

	return 0;
}

4 拷贝构造函数

4.1 概念

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

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 = 1;
	int _month = 1;
	int _day = 1;
};

void func1(Date d)  // d和d1不是同一个对象
{
	d.Print();      // d的改变不会影响d1
}

int main()
{
	Date d1(2024, 9, 26);
	func1(d1);
	
	return 0;
}

日期类可以正常拷贝(浅拷贝)没问题,但是栈类,浅拷贝会有问题

typedef int DataType;
class Stack
{
public:
	Stack(size_t capacity = 3)
	{
		_array = (DataType*)malloc(sizeof(DataType) * capacity);
		if (NULL == _array)
		{
			perror("malloc申请空间失败!!!");
			return;
		}
		_capacity = capacity;
		_size = 0;
	}
	void Push(DataType data)
	{
		// CheckCapacity();
		_array[_size] = data;
		_size++;
	}
	// 其他方法...
	~Stack()
	{
		cout << "~Stack()" << endl;

		free(_array);
		_array = NULL;
		_size = _capacity = 0;
	}
private:
	DataType* _array;
	int _capacity;
	int _size;
};

void func2(Stack s)
{

}

int main()
{
	Stack s1;

	// s1传递给func2时,是浅拷贝或者叫值拷贝
	// _arry进行浅拷贝时,析构函数会调用两次(析构函数是自动调用)
	// func2先free一次,main函数free一次
	func2(s1);

	return 0;
}

上述问题怎么解决了?(free两次的问题)

第一种解决方案,加一个引用(s的改变会影响s1)

void func2(Stack& s)
{
		
}

上述解决方案有一个问题,如果我期望s的改变,不影响s1,该怎么办?

答:使用拷贝构造。

自定义类型传值传参,一定要调用拷贝构造

4.2 拷贝构造特征

  1. 拷贝构造函数是构造函数的一个重载形式。
  2. 拷贝构造函数的参数只有一个且必须是同类类型对象的引用,使用传值方式编译器直接报错,因为会引发无穷递归调用。
class Date
{
public:
	// 构造函数
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	// 拷贝构造
	// Date d2(d1);
	Date(const Date& d)   // 推荐加一个const(权限的缩小)
	{
		cout << "Date(Date& d)" << endl;

		_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)
{
	d.Print();
}

int main()
{
	Date d1(2024, 9, 26);
	// 传值传参的时候,一定会调用拷贝构造
	func1(d1);
	
	// 以下两个写法是等价的,都是拷贝构造
	Date d2(d1);
	Date d3 = d1;
	return 0;
}
typedef int DataType;
class Stack
{
public:
	// 构造函数
	Stack(size_t capacity = 3)
	{
		_array = (DataType*)malloc(sizeof(DataType) * capacity);
		if (NULL == _array)
		{
			perror("malloc申请空间失败!!!");
			return;
		}
		_capacity = capacity;
		_size = 0;
	}

	Stack(const Stack& s) // 推荐加一个const(权限的缩小)
	{
		cout << "Stack(Stack& s)" << endl;
		// 深拷贝
		_array = (DataType*)malloc(sizeof(DataType) * s._capacity);
		if (NULL == _array)
		{
			perror("malloc申请空间失败!!!");
			return;
		}
		memcpy(_array, s._array, sizeof(DataType) * s._size);
		_size = s._size;
		_capacity = s._capacity;
	}

	void Push(DataType data)
	{
		_array[_size] = data;
		_size++;
	}

	~Stack()
	{
		cout << "~Stack()" << endl;

		free(_array);
		_array = NULL;
		_size = _capacity = 0;
	}

private:
	DataType* _array;
	int _capacity;
	int _size;
};

void func2(Stack s)
{
	s.Push(1);
	s.Push(2);
}

int main()
{
	Stack s1;
	// 传值传参的时候,会先调用拷贝构造
	// func2里面s的改变不会影响s1
	func2(s1);

	// 拷贝构造
	Stack s2(s1);
	return 0;
}
  1. 若未显式定义,编译器会生成默认的拷贝构造函数。 默认的拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝。

编译器默认生成的拷贝构造跟之前的构造函数特性不一样:

  1. 内置类型, 值拷贝
  2. 自定义类型,调用它的拷贝

总结:Date不需要我们实现拷贝构造,默认生成的就可以用,Stack需要我们自己实现深拷贝的拷贝构造,默认生成会出问题(浅拷贝,会释放两次)

5 赋值运算符重载

比较两个日期的大小

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 DateLess(const Date& x1, const Date& x2)
{
	if (x1._year < x2._year)
	{
		return true;
	}
	else if (x1._year == x2._year && x1._month < x2._month)
	{
		return true;
	}
	else if (x1._year == x2._year && x1._month == x2._month && x1._day < x2._day)
	{
		return true;
	}
	else
	{
		return false;
	}
}

int main()
{
	Date d1(2024, 9, 27);
	Date d2(2023, 9, 27);

	//d1 < d2;
	cout << DateLess(d1, d2) << endl;
	return 0;
}

我想用一下下面的代码

cout << (d1 < d2) << endl;

只能让编译器多做点事情!!!

5.1 运算符重载

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

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

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

// 运算符重载    (重载有重新定义的意思)
bool operator<(const Date& x1, const Date& x2)
{
	if (x1._year < x2._year)
	{
		return true;
	}
	else if (x1._year == x2._year && x1._month < x2._month)
	{
		return true;
	}
	else if (x1._year == x2._year && x1._month == x2._month && x1._day < x2._day)
	{
		return true;
	}
	else
	{
		return false;
	}
}

int main()
{
	Date d1(2024, 9, 27);
	Date d2(2023, 9, 27);
	cout << (d1 < d2) << endl;
	// 加括号是因为流插入运算符优先级最高

	// 等价于下面的
	cout << (operator<(d1, d2)) << endl;

	return 0;
}

注意:

  1. 不能通过连接其他符号来创建新的操作符:比如operator@
  2. 重载操作符必须有一个自定义类型参数
  3. 用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不 能改变其含义
  4. 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this
  5. 不能改变操作符的,操作数个数。一个操作符是几个操作数,那么重载的时候就有几个参数。
  6. .* :: sizeof ?: .这五个运算符不能重载。(面试选择题会出现)

如果成员函数私有不能访问怎么办?上面的operator会报错。

答:将operator定义为类成员函数。

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

	// d1 < d2;  转换为:d1.operator<(d2)
	// d1用this替代了(而this又可以省略),然后d2被d替代了
	bool 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;
		}
		else
		{
			return false;
		}
	}

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

int main()
{
	Date d1(2024, 9, 27);
	Date d2(2023, 9, 27);

	cout << (d1 < d2) << endl;
	cout << (d1.operator<(d2)) << endl;
	return 0;
}

来一段长脑子的代码:

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

	bool 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;
		}
		else
		{
			return false;
		}
	}

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

	// d1 <= d2    
	// this是d1的地址,*this就是d1
	bool operator<=(const Date& d)
	{
		return *this < d || *this == d;
	}

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

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

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

	int GetMonthDay(int year, int month)
	{
		// 这里的13很细节和月份一一对应上了
		int monthArray[13] = { 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 monthArray[month];
	}

	Date& operator+=(int day)
	{
		_day += day;
		while (_day > GetMonthDay(_year, _month))
		{
			// 月进位
			_day -= GetMonthDay(_year, _month);
			++_month;

			// 月满了
			if (_month == 13)
			{
				++_year;
				_month = 1;
			}
		}
		return *this;
	}

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

		//tmp._day += day;
		//while (tmp._day > GetMonthDay(tmp._year, tmp._month))
		//{
		//	// 月进位
		//	tmp._day -= GetMonthDay(tmp._year, tmp._month);
		//	++tmp._month;

		//	// 月满了
		//	if (tmp._month == 13)
		//	{
		//		++tmp._year;
		//		tmp._month = 1;
		//	}
		//}
		//return tmp;
	}

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

int main()
{
	Date d1(2024, 9, 27);
	Date d2(2023, 9, 27);

	cout << (d1 < d2) << endl;
	cout << (d1 == d2) << endl;

	//Date ret = d1 += 50;
	//ret.Print();
	//d1.Print();

	Date ret = d1 + 50;
	ret.Print();
	d1.Print();

	return 0;
}

今天笔记写完了!!!!
要长脑子了!!!!!进化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值