C++类和对象(中)

🌈个人主页@ꪔ小林Y

个人专栏《C++小白闯关日记》《C语言小白闯关日记》,《数据结构入门------从原理到实战》

🍀代码信条 :每一行代码都是成长的脚印👣,每一次调试成功都是对坚持的回应

目录

C++类和对象(中)

类的默认成员函数

默认成员函数就是用户没有显式实现,编译器会自动生成的成员函数称为默认成员函数。一个类,我们不写的情况下默认生成6个默认成员函数。

6个默认成员函数:

  • 初始化和清理:
    构造函数 主要完成初始化工作;
    析构函数主要完成清理工作。
  • 拷贝复制:
    拷贝构造 是使用同类对象初始化创建对象;
    赋值重载主要是把一个对象赋值给另一个对象。
  • 取地址重载:
    主要是普通对象和const对象取地址,这两个很少会自己实现

1.构造函数

构造函数是特殊的成员函数,需要注意的是,构造函数虽然名称叫构造,但是构造函数的主要任务并不是开空间创建对象,而是对象实例化时初始化对象。构造函数的本质是要替代我们以前Stack和Data类中书写的Init函数的功能,构造函数自动调用的特点就完美的替代了Init。

构造函数的特点:

  • 1.函数名类名相同。
  • 2.无返回值。(返回值什么都不用给,void也不用写)
  • 3.对象实例化 时系统会自动调用对应的构造函数
  • 4.构造函数可以重载。如下代码
cpp 复制代码
```cpp
class Date
{
public:
	Date()
	{
		_year = 1;
		_month = 1;
		_day = 1;
	}
	//两个Date构成函数重载
   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 d2(2025, 7, 31);
	d1.Print();
	d2.Print();
	return 0;
}
  • 5.如果类中没有显式定义构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定义编译器将不再生成。
  • 6.无参构造函数全缺省构造函数 ,我们不写构造时编译器默认生成的构造函数都叫做默认构造函数。但是这三个不同时存在,只能存在一个。总结一下就是不穿实参就可以调用的构造就叫默认构造
  • 7.编译器默认生成的构造
    (1)对内置类型成员变量的初始化没有要求 ,也就是说是否初始化是不确定的,看编译器。
    (2)对于自定义类型成员变量,要求调用这个成员变量的默认构造函数初始化。
    (C++把类型分成内置类型自定义类型 。内置类型就是语言提供的原生数据模型,如:int/char/double/指针 等,自定义类型就是我们使用class/struct等关键字自己定义的类型) ,如下代码:
cpp 复制代码
class Date
{
public:
	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
private:
	//内置类型
	int _year;
	int _month;
	int _day;
};
class Stack
{
public:
	Stack()
	{
		_a = nullptr;
		_top = 0;
		_capacity = 0;
	}
private:
	int* _a;
	int _top;
	int _capacity;
};
//两个栈实现一个队列
class MyQueue
{
private:
	//自定义类型
	Stack _pushst;
	Stack _popst;
	int _size;
};
int main()
{
	Date d1;
	d1.Print();
	MyQueue q;
	return 0;
}

2.析构函数

析构函数与构造函数功能相反,析构函数不是完成对对象本身销毁,比如局部对象是存在栈帧的,函数结束栈帧销毁,它就释放了。C++规定对象在销毁时会自动调用析构函数,完成对象中资源的清理释放工作。析构函数的功能比我们之前Stack实现的Destroy功能,而像Date没有Destroy,其实就是没有资源需要释放,所以严格说Date是不需要析构函数的。

析构函数的特点:

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

3.拷贝构造函数

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

拷贝构造的特点:

  • 1.拷贝构造函数是构造函数的一个重载
  • 2.拷贝构造函数的第一个参数必须是当前类类型对象的引用,使用传值方式编译器直接报错,因为语法逻辑上会引发无穷递归调用。拷贝构造函数也可以多个参数,但是第一个参数必须是类类型对象的引用,后面的参数必须有缺省值。
  • 3.C++规定自定义类型对象进行拷贝 行为必须调用拷贝构造 ,所以这里自定义类型传值传参传值返回都会调用拷贝构造完成。
  • 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(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;
};
//自定义类型,传值传参要调用拷贝构造
void Func(Date& d)
{
}
int main()
{
	Date d1(2025, 8, 1);
	//拷贝构造
	Date d2(d1);//Date d3=d1
	Func(d1);
	return 0;
}
  • 5.补充一下深拷贝 就是对指向的资源也进行拷贝 。像Date这样的类成员变量全是内置类型没有指向什么资源,编译器自动生成的拷贝构造就可以完成需要的拷贝,所以不需要我们显示实现拷贝构造。像Stack这样的类,虽然也都是内置类型,但是** _a指向了资源,编译器自动生成的拷贝构造完成的浅拷贝不符合我们的需求**,所以需要自己实现深拷贝。如果一个类显示实现了析构并释放资源,那么就需要显示写拷贝构造,否则不需要。
  • 6.传值返回会产生一个临时对象调用拷贝构造,传值引用返回,返回的是返回对象的别名,没有产生拷贝。但是如果返回对象是一个当前函数局部域的局部对象 ,函数结束就销毁了,那么使用引用返回是有问题的,这是的引用相当于一个野引用,类似一个野指针一样。传引用返回可以减少拷贝,但是一定要确保返回对象,在当前函数结束后还在,才能用引用返回

4.赋值运算符重载

4.1运算符重载

  • 当运算符被用于类类型的对象时,C++语言允许我们通过运算符重载的形式指定新的含义。C++规定类类型对象使用运算符时,必须转换成调用对应运算符重载,若没有对应的运算符重载,则会编译报错。
  • 运算符重载是具有特殊名字的函数,他的名字是由operator 和后面要定义的运算符 共同构成。和其他函数一样,它也具有其返回类型参数列表 以及函数体
  • 重载运算符函数的参数个数和该运算符作用的运算对象数量一样多。一元运算符有一个参数,二元运算符有两个参数二元运算符的左侧运算对象传给第一个参数,右侧运算对象传给第二个参数
cpp 复制代码
bool operator==(const Date& x1, const Date& x2)
{
	return _year == d._year
	&& _month == d._month
	&& _day == d._day;
}
int main()
{
	Date d1(2026, 8, 1);
	Date d2(2026, 10, 1);
	d1 == d2;
	operator==(d1, d2);
	return 0;
}

这样写是编译不出来的,因为_year...是私有的,但是我们可以换种方式,把它们放在类里面:

cpp 复制代码
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	Date(Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
	void Print()
	{
		cout << _year << "-" << _month<<"-" << _day << endl;
	}
	bool operator==(const Date& d)
	{
		return _year == d._year
			&& _month == d._month
			&& _day == d._day;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d1(2026, 8, 1);
	Date d2(2026, 10, 1);
	cout<<(d1 == d2)<<endl;
	d1.operator==( d2);
	return 0;
}
  • 如果一个重载运算符函数是成员函数,则它的第一个运算对象默认传给隐式的this指针,因此运算符重载作为成员函数时,参数比运算对象少一个
  • 运算符重载以后,其优先级和结合性对应的内置类型运算符保持一致
  • 不能通过连接语法中没有的符号来创建新的操作符:比如operator@
复制代码
     (1).*       (2)::         (3) sizeof        (4)?:        (5).              

注意以上5个运算符不能重载 。(常考)

  • 重载操作符至少有一个类类型参数,不能通过运算符重载改变内置类型对象的含义 ,如: int operator+(int x, int y)
  • 一个类需要重载哪些运算符,是看哪些运算符重载后有意义,比如Date类重载operator﹣就有意义,但是重载operator+就没有意义。
  • 重载++运算符时,有前置++和后置++,运算符重载函数名都是operator++,无法很好的区分。C++规定,后置++重载时,增加一个int形参,跟前置++构成函数重载,方便区分 。重载<<和>>时,需要重载为全局函数,因为重载为成员函数,this指针默认抢占了第一个形参位置,第一个形参位置是左侧运算对象,调用时就变成了 对象<<cout,不符合使用习惯和可读性。重载为全局函数把ostream/istream放到第一个形参位置就可以了,第二个形参位置当类类型对象。

4.2赋值运算符重载

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

赋值运算符重载的特点:

  • 1.赋值运算符重载是一个运算符重载,规定必须重载为成员函数 。赋值运算重载的参数建议写成const当前类类型引用,否则会传值传参会有拷贝
  • 2.有返回值,且建议写成当前类类型引用,引用返回可以提高效率,有返回值目的是为了支持连续赋值场景。
  • 3.没有显式实现时,编译器会自动生成一个默认赋值运算符重载,默认赋值运算符重载行为跟默认拷贝构造函数类似,对内置类型成员变量会完成值拷贝/浅拷贝(一个字节一个字节的拷贝),对自定义类型成员变量会调用他的赋值重载函数。
    实现:
cpp 复制代码
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;
	}
	//d1=d3=d5
	Date& operator=(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
		return *this;
	}
	void Print()
	{
		cout << _year << "-" << _month<<"-" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d1(2026, 8, 1);
	//赋值运算符重载实现
	Date d3(2026, 3, 1);
	d1 = d3;
	Date d5(2026, 2, 1);
	d1 = d3 = d5;
	return 0;
}

4.3日期类实现

cpp 复制代码
//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();
	int GetMonthDay(int year,int month)
		{
		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 % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
		{
			return 29;
		}
		else
		{
			return monthDayArray[month];
		}
		}
	bool CheckDate()
	{
		if (_month < 1 || _month>12)
			return false;
		if (_day<1 || _day>GetMonthDay(_year, _month))
			return false;

		return true;
	}
	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 day);
	Date operator+(int day);

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

	//d1-d2
	int operator-(const Date& d);

	//++d1->d1.operator++()
	Date& operator++();
	//d1++->d1.operator++(0)
	//为了区分,构成重载,给后置++,强行增加了一个int形参
	//这里不需要写形参名,因为接收值是多少不重要,也不需要用
	//这个参数仅仅是为了跟前置++构成重载区分
	Date operator++(int);

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

	//后置--多加一个类型
	Date operator--(int);
private:
	int _year;
	int _month;
	int _day;
};
//void operator<<(ostream& out, const Date& d);//这个运算符不能放成成员函数,只能放成全局函数.
//因为cout要占据第一个参数位置才符合可读性
ostream& operator<<(ostream& out, const Date& d);

istream& operator>>(istream& in, Date& d);
cpp 复制代码
//Date.cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include"Date.h"
Date::Date(int year, int month, int day)
{
	_year = year;
	_month = month;
	_day = day;
	if (!CheckDate())
	{
		cout << "非法日期:>" << *this;
	}
}
void Date::Print()
{
	cout << _year << "-" << _month << "-" << _day << endl;
}
//d1+=100
//Date Date::operator+=(int day)
//{
//	_day += day;
//	while (_day > GetMonthDay(_year, _month))
//	{
//		_day -= GetMonthDay(_year, _month);
//		++_month;
//		if (_month == 13)
//		{
//			++_year;
//			_month = 1;
//		}
//	}
//	return *this;
//}//这里运行完我们发现d1也变了

//d1+100
Date Date::operator+(int day)
{
	Date tmp(*this);
	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;
}

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

//d1-100
Date Date::operator-(int day)
{
	Date tmp = *this;//拷贝构造
	tmp -= day;
	return tmp;
}


//++d1->d1.operator++();
Date& Date::operator++()
{
	*this += 1;
	return *this;
}
//d1++->d1.operator++(0)
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;
}



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

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

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



//d1-d2
int Date::operator-(const Date& d)
{
	Date max = *this;
	Date min = d;
	int flag = 1;
	if (*this < d)
	{
		min = *this;
		max = d;
		flag = -1;
	}
	int day = 0;
	while (min != max)
	{
		++min;
		++day;
	}
	return day * flag;
}
ostream& operator<<(ostream& out, const Date& d)//这里的out是一个形参,不一定非得写成out
{
	out << d._year << "/" << d._month << "/" << d._day << '\n';
	return out;
}//通过友元函数声明解决

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

		if (d.CheckDate())
		{
			break;
		}
		else
		{
			cout << "输入日期非法,请重新输入:" << endl;
		}
	}
	return in;
}
cpp 复制代码
//Test.cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include"Date.h"
void TestDate1()
{
	Date d1(2026, 4, 12);
	d1 -= 50;
	d1.Print();

	//日期-天数
	Date d2 = d1 - 50;
	d1.Print();


	//日期-=
	Date d3(2025, 9, 8);
	d3 -= 2000;
	d3.Print();

}
void TestDate2()
{
	//日期--
	Date d1(2026, 4, 12);
	Date d3 = --d1;//d1.operator--();前置
	d1.Print();
	d3.Print();
	Date d2 = d1--;//d1.operator--(1);后置。传什么值根本不重要,因为用不到
	d1.Print();
	d2.Print();

	//日期相减
	Date d4(2026, 4, 12);
	Date d5(2026, 5, 1);
	cout << d4 - d5 << endl;
	Date d6(2026, 7, 1);
	cout << d4 - d6 << endl;
}
void TestDate3()
{
	Date d1(2026, 4, 12);
	Date d2(2026, 4, 11);

	//流插入(输出)
	//operator<<(cout, d1);
	//cout << d1 ;
	cout << d1<<d2;//两次函数调用需要修改声明定义
	//虽然可以跑,但是不符合可读性
	//d1.operator<<(cout);
	//d1<<cout;

	//流提取(输入)
	cin >> d1 >> d2;
	cout << d1 << d2;
}
int main()
{
	//日期加天数
	//Date d1(2025, 8, 1);
	//Date d2 = d1 + 100;
	//d1.Print();
	//d2.Print();

	//Date d3(2025, 8, 1);
	//Date d4 = d3 + 100;
	//d3.Print();
	//d4.Print();

	//日期++
	//Date d1(2025, 8, 1);
	//Date ret1 = d1++;
	//ret1.Print();
	//d1.Print();

	//Date d2(2025, 8, 1);
	//Date ret2 = ++d1;
	//ret2.Print();
	//d1.Print();

	//Date d6 = d1.operator+(100);
	//Date d6 = d1 + 100;
	////Date d6=operator+(d1,100);
	TestDate2();
	return 0;
}

5.取地址运算符重载

5.1const成员函数

  • 将const修饰的成员函数称之为const成员函数,const修饰成员函数放到成员函数参数列表的后面。
  • const实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。例如const修饰Date类的Print成员函数,Print隐含的this指针由Date* const this变为const Date* const this
  • 因此,不修改成员变量的成员函数尽量都加上const,这样的话普通对象和const对象都可以调用这个const成员函数

5.2取地址运算符重载

  • 取地址运算符重载分为普通取地址运算符重载和const取地址运算符重载,一般这两个函数编译器自动生成的就够用了,不需要去显示实现。除非一些很特殊的场景,比如不想让别人取到当前类的地址,就可以自己实现一份,胡乱返回一个地址
cpp 复制代码
Date* operator&()
{
	retyrn this;
	//return nullptr;
}
const Date* operator&()const
{
	return this;
	//return nullptr;
}

🎊本期C++类和对象(中)的内容就结束了。如果文中有表述不准的地方,或是你有更清晰的理解思路,强烈欢迎在评论区留言交流------ 技术路上多碰撞,才能更快进步

觉得内容对你有帮助的话,别忘了点赞❤️➕收藏🌟,方便后续回顾复习;想跟着一起系统学习数据结构的朋友,也可以点击关注,下一期我们会聚焦更进一步的学习。不见不散✌️

相关推荐
Tairitsu_H1 小时前
C++:优先队列的模拟实现
开发语言·c++·stl·优先队列
lzh200409191 小时前
效率与安全并重:C++ 线程安全
linux·c++
Shan12051 小时前
RAII妙用:使用标准库的包装器
开发语言·c++
Hua-Jay1 小时前
OpenCV联合C++/Qt 学习笔记(十八)----二维码检测及积分图像
c++·笔记·qt·opencv·学习
Rabitebla1 小时前
深入理解 C++ STL:stack 和 queue 的底层原理与实现
c语言·开发语言·数据结构·c++·算法
誰能久伴不乏2 小时前
从底层看透音视频架构:FFmpeg 实时视频推流深度解析
linux·c++·tcp/ip·ffmpeg
此生决int2 小时前
C++快速上手java备战期末考——初识java
java·c++·期末复习
落羽的落羽2 小时前
【算法札记】练习 | Week3
linux·服务器·数据结构·c++·人工智能·算法·动态规划
计算机安禾2 小时前
【c++面向对象编程】第13篇:继承(三):同名隐藏与作用域覆盖
开发语言·c++·iphone