【C++】类和对象(二)

1.类的默认成员函数

默认成员函数就是用户没有显式实现,编译器会自动生成的成员函数

一个类在什么都不写的情况下编译器会默认生成6个默认成员函数。6个中最重要的是前4个,后两个相对不重要,了解即可。C++11之后还增加了两个默认成员函数:移动构造和移动赋值。

学习默认成员函数要从两个方面学习:

  • 我们不写时,编译器默认生成的函数行为是什么,是否满足我们的需求
  • 编译器默认生成的函数不满足我们的需求时,我们如何自己实现

2.构造函数

构造函数是特殊的成员函数。构造函数的作用是在对象实例化时初始化对象。

构造函数的特点

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

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

cpp 复制代码
#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;
	}

	// 全缺省构造函数
	// 无参构造函数和全缺省构造函数不能同时存在,构成函数重载但存在调用歧义
	//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;
};

int main() {
	// 如果只留下有参构造函数,无参构造和全缺省构造都注释掉,运行程序会报错
	// "Date": 没有合适的默认构造函数可用
	Date d1;				// 调用默认构造
	Date d2(2026, 1, 15);	// 调用带参的构造函数\

	// 通过无参构造函数创建对象时对象后面不用跟括号
	// 否则编译器无法区分这里是函数声明还是实例化对象
	Date d3();

	d1.Print();
	d2.Print();
	return 0;
}
cpp 复制代码
#include<iostream>
using namespace std;

typedef int STDataType;
class Stack {
public:
	Stack(int n = 4) {
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (nullptr == _a) {
			perror("malloc fail!");
			return;
		}
		_capacity = n;
		_top = 0;
	}
	
	// ...

private:
	STDataType* _a;
	size_t _capacity;
	size_t _top;
};

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

int main() {

	MyQueue mq;

	return 0;
}

总结:大部分情况下编译器生成的构造函数都不能满足需求,极少数情况(如上面代码的MyQueue可以满足),大部分情况都需要自己实现构造函数(应写尽写)

3.析构函数

析构函数与构造函数功能相反。 C++规定对象在销毁时会自动调用析构函数,完成对象中资源的清理释放工作。析构函数的功能类似于之前Stack代码中的Destroy功能,而之前写的Date类没有Destroy,是因为没有资源需要释放,严格来说Date类不需要析构函数。(有资源申请的类需要析构函数)

析构函数的特点

  1. 析构函数名是类名前加上字符~
  2. 无参数无返回值(和构造函数类似,也不需要加void)
  3. 一个类只能有一个析构函数,若未显式定义,系统会自动生成默认的析构函数
  4. 对象生命周期结束时,系统会自动调用析构函数
  5. 跟构造函数类似,编译器自动生成的析构函数对内置成员不做处理,自定义成员会调用他的析构函数
  6. 当我们显式写析构函数,对于自定义类型也会调用他的析构。也就是说自定义类型成员无论什么情况都会自动调用析构函数
  7. 如果类中没有资源申请,析构函数可以不写,直接使用编译器生成的默认析构函数,如Date;如果默认生成的析构函数就可以用,也不需要显式写析构,如MyQueue;但有资源申请时,一定要自己写析构,否则会造成资源泄露,如Stack
  8. 一个局部域的多个对象 ,C++规定后定义的先析构
cpp 复制代码
#include<iostream>
using namespace std;

typedef int STDataType;
class Stack {
public:
	Stack(int n = 4) {
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (nullptr == _a) {
			perror("malloc fail!");
			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;
}

4.拷贝构造函数

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

拷贝构造的特点

  1. 拷贝构造函数是构造函数的一个重载
  2. 拷贝构造函数的第一个参数必须是类类型对象的引用(引用传参),使用传值方式编译器直接报错,因为语法逻辑上会引发无穷递归调用。拷贝构造函数也可以有多个参数,但是第一个参数必须是类类型对象的引用,后面的参数必须有缺省值。
  3. C++规定自定义类型对象进行拷贝行为必须调用拷贝构造,所以自定义类型传值传参和传值返回都会调用拷贝构造完成
  4. 若未显式定义拷贝构造,编译器会自动生成拷贝构造函数。自动生成的拷贝构造对内值类型成员变量会完成值拷贝/浅拷贝 (一个字节一个字节的拷贝),对自定义类型成员变量会调用它的拷贝构造
  5. 如果一个类显式实现了析构并释放资源,那么这个类就需要写拷贝构造,否则就不需要。
  6. 传值返回会产生一个临时对象调用拷贝构造 ,传值引用返回,返回的是返回对象的别名(引用),没有产生拷贝。但是如果返回对象是一个当前函数局部域的局部对象,函数结束就销毁了,那么使用引用返回就相当于野引用,类似于野指针。传引用返回可以减少拷贝,但是要确保返回对象在当前函数结束后还存在才能引用返回。
cpp 复制代码
#include<iostream>
using namespace std;

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

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

	Date(Date* d) {
		_year = d->_year;
		_month = d->_month;
		_day = d->_month;
	}

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

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

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

// 返回tmp的别名,但函数结束时tmp被销毁,
// 相当于野引用,类似于野指针
// 此处可将tmp定义为static,或将tmp作为参数传入
Date& Func2() {
	Date tmp(2026,1,15);
	tmp.Print();

	return tmp;
}

int main() {
	Date d1(2026, 1, 15);
	// C++规定自定义类型对象进行拷贝行为必须调用拷贝构造,所以这里传值传参要调用拷贝构造
	// 所以这里的d1传值传参给d要调用拷贝构造完成拷贝,传引用传参可以减少这里的拷贝
	Func1(d1);

	cout << &d1 << endl;

	// 这里可以完成拷贝,但不是拷贝构造,只是普通的构造
	Date d2(&d1);
	d1.Print();
	d2.Print();

	// 这样写才是拷贝构造,通过同类型的对象初始化构造,而不是指针
	Date d3(d1);
	d3.Print();

	// 也可以这样写,这也是拷贝构造
	Date d4 = d1;
	d4.Print();

	// Func2返回了一个局部对象tmp的引用作为返回值
	// Func2函数结束,tmp对象就销毁了,相当于一个野引用
	Date ret = Func2();
	ret.Print();

	return 0;
}
cpp 复制代码
#include<iostream>
using namespace std;

typedef STDataType;
class Stack {
public:
	Stack(int n = 4) {
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		if (nullptr == _a) {
			perror("malloc fail!");
			return;
		}
		_capacity = n;
		_top = 0;
	}

	Stack(const Stack& st) {

		_a = (STDataType*)malloc(sizeof(STDataType)*st._capacity);
		if (_a == nullptr) {
			perror("malloc fail!");
			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 == NULL) {
				perror("realloc fail!");
				return;
			}
			_a = tmp;
			_capacity = newCapacity;
		}
		_a[_top++] = x;
	}

	~Stack() {
		cout << "~Stack()" << endl;
		free(_a);
		_a = nullptr;
		_top = _capacity = 0;
	}

private:
	STDataType* _a;
	size_t _capacity;
	size_t _top;
};

// 两个Stack实现队列
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;
}

函数传参尽可能用引用,如果不改变,尽可能用const

5.赋值运算符重载

5.1运算符重载

  1. 当运算符被用于类类型对象时,C++语言允许我们通过运算符重载的形式指定新的含义。C++规定类类型对象使用运算符时,必须转换成调用对应运算符重载,若没有对应运算符重载则编译报错。
  2. 运算符重载是具有特殊名字的函数 ,它的名字是由operator和后面要定义的运算符共同构成 。和其他函数一样,他也具有其返回类型和参数列表以及函数体
  3. 重载运算符的参数个数和该运算符作用的运算数量一样多 。一元运算符有一个参数,二元运算符有两个参数,二元运算符的左侧运算对象传给第一个参数,右侧运算对象传给第二个参数
  4. 如果一个重载运算符函数是成员函数,则它的第一个运算对象默认传给隐式的this指针,因此重载运算符作为成员函数时,参数比运算对象少一个。
  5. 运算符重载后,优先级与结合性不变,与其对应的内置类型的运算符保持一致
  6. 不能通过连接语法中没有的符号来创建新的运算符,比如operator@
  7. ① .* ② :: ③ sizeof ④ ?: ⑤ . 这五个运算符不能被重载
  8. 重载运算符至少有一个类类型的参数,不能通过运算符重载改变内置类型对象的含义,如int operator+(int x, int y)
  9. 一个类需要重载哪些运算符,是看哪些运算符重载后有意义,比如Date类重载operator-就有意义,但是重载operator+就没有意义
  10. 重载++运算符时,有前置++和后置++,运算符重载函数名都是operator++,无法很好的区分,C++规定,后置++重载时,增加一个int形参,跟前置++构成函数重载,方便区分
  11. 重载<<和>>时,需要重载为全局函数,因为如果重载为成员函数,this指针默认抢占了第一个形参位置,第一个形参位置是左侧运算对象,调用时就变成了对象<<cout,不符合使用习惯和可读性。重载为全局函数把ostream/istream放到第一个形参位置就可以了,第二个形参位置是类类型对象。
cpp 复制代码
#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 Print() {
		cout << _year << "/" << _month << "/" << _day << endl;
	}

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

//运算符重载为全局函数时无法访问私有变量
// 有几种解决方法:
// 1. 成员变量设置为公有(不推荐)
// 2. Date类提供Get...()函数(java常用)
// 3. 友元函数
// 4. 重载为成员函数
//bool operator==(const Date& d1, const Date& d2) {
//	return d1._year == d2._year
//		&& d1._month == d2._month
//		&& d1._day == d2._day;
//}

int main() {
	return 0;
}
cpp 复制代码
#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 Print() {
		cout << _year << "/" << _month << "/" << _day << endl;
	}

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

	Date& operator++() {
		cout << "前置++" << endl;
		return *this;
	}

	Date operator++(int) {
		Date tmp;
		cout << "后置++" << endl;
		return tmp;
	}

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

int main() {
	Date d1(2026, 1, 17);
	Date d2(2026, 1, 16);

	// 运算符重载可以显式调用
	d1.operator==(d2);
	// 编译器会转换成d1.operator==(d2);
	d1 == d2;

	// 编译器会转换成d1.operator++();
	++d1;
	// 编译器会转换成d1.operator++(0);
	d1++;

	return 0;
}

5.2赋值运算符重载

赋值运算符重载是一个默认成员函数 ,用于完成两个已经存在的对象直接的拷贝赋值。赋值运算符重载和拷贝构造不一样,拷贝构造适用于一个对象拷贝初始化给另一个要创建的对象。

赋值运算符重载的特点

  1. 赋值运算符重载是一个运算符重载 ,规定必须重载为成员函数 。赋值运算符重载的参数建议写成const当前类类型引用,否则0传值传参会有拷贝。
  2. 有返回值,且建议写成当前类类型的引用 (赋值返回值是左操作数),引用返回可以提高效率,有返回值目的是为了支持连续赋值场景
  3. 没有显式实现时,编译器会自动生成一个默认赋值运算符重载 ,默认赋值运算符重载行为跟默认拷贝构造函数类似,对内置类型成员变量会完成值拷贝/浅拷贝(一个字节一个字节的拷贝),对自定义类型成员变量会调用它的赋值重载函数
  4. 如果一个类显式实现了析构并释放资源,那么它就需要显式写赋值运算符重载。
cpp 复制代码
#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) {
		cout << "Date(const Date& d)" << endl;
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}

	// 传引用返回减少拷贝
	Date& operator=(const Date& d) {
		// 当this和&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(2026, 1, 17);
	Date d2(d1);

	Date d3(2026, 1, 16);

	// 赋值重载拷贝
	d1 = d3;

	// 拷贝构造
	Date d4 = d1;

	return 0;
}

5.3日期类实现

Date.h

cpp 复制代码
#pragma once
#include<iostream>
using namespace std;

#include<assert.h>

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();

	// 因为这个函数经常调用,所以定义在类里。
	// 定义在类里默认为inline
	int GetMonthDay(int year, int month) {
		assert(month > 0 && month < 13);
		// 数组定义为static,无需每次调用函数都创建新数组
		static int monthDayArray[13] = { -1,31,28,31,30,31,30,31,31,30,31,30,31 };
		// 月份为2月且为闰年返回29
		// 此处month==2写前面可以减少比较次数(&&前面的条件不符合时后面就不再比较)
		if (month == 2 && (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
			return 29;
		}
		else {
			return monthDayArray[month];
		}
	}

	bool CheckDate();

	// 运算符重载
	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 day);
	Date operator+(int day) const;
	// d1 -= 天数
	Date& operator-=(int day);
	Date operator-(int day) const;
	// d1 - d2
	int operator-(const Date& d) const;
	// ++d1 -> d1.operator++()
	Date& operator++();
	// d1++ -> d1.operator++(0)
	// 为了区分,构成重载,给后置++加了一个int形参
	// 不需要写形参名,因为接收值是几不重要,也不需要用
	// 这个参数只是为了和前置++进行区分
	Date operator++(int);

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

	// 流插入
	// 不建议,如果定义成成员函数,第一个参数是Date* this,使用c<<cout不符合使用习惯\
	// 所以流插入和流提取的重载定义成全局函数
	// 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

cpp 复制代码
#include"Date.h"

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

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

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

void Date::Print() {
	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;
}

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 _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

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

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) {
			_month = 1;
			++_year;
		}
	}
	return *this;
}

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) {
			--_year;
			_month = 12;
		}
		_day += GetMonthDay(_year, _month);
	}
	return *this;
}

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

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

// 后置++有拷贝,尽量减少使用后置++
Date Date::operator++(int) {
	Date tmp(*this);
	*this += 1;
	return tmp;
}

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

Date Date::operator--(int) {
	Date tmp(*this);
	*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 n + flag;
}

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

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

6.取地址运算符重载

6.1const成员函数

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

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

cpp 复制代码
#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 Print() const{                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
		cout << _year << "/" << _month << "/" << _day << endl;
	}

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

int main() {
	// 非const对象也可以调用const成员函数,是一种权限的缩小
	Date d1(2026, 1, 17);
	d1.Print();

	const Date d2(2026, 1, 16);
	d2.Print();

	return 0;
}

6.2取地址运算符重载

取地址运算符重载分为普通取地址运算符重载const取地址运算符运算符重载 ,一般这两个函数编译器自动生成的就可以用,不需要显式实现(如果要显式实现,两个都要实现)。除非一些特殊场景,比如不想让别人取到当前类对象的地址时,可以自己实现取地址运算符重载随便返回一个地址

相关推荐
Duang007_2 小时前
【万字学习总结】API设计与接口开发实战指南
开发语言·javascript·人工智能·python·学习
一叶星殇2 小时前
C# .NET 如何解决跨域(CORS)
开发语言·前端·c#·.net
Elieal2 小时前
Java项目密码加密实现详解
java·开发语言
shhpeng2 小时前
go mod vendor命令详解
开发语言·后端·golang
Java程序员威哥2 小时前
用Java玩转机器学习:协同过滤算法实战(比Python快3倍的工程实现)
java·开发语言·后端·python·算法·spring·机器学习
GeekyGuru2 小时前
C++跨平台开发的核心挑战与应对策略
开发语言·c++
Howrun7772 小时前
信号量(Semaphore)
开发语言·c++·算法
leaves falling2 小时前
c语言-动态内存管理
c语言·开发语言
Lution Young2 小时前
Qt隐式共享产生的问题
开发语言·qt