今天的内容主要是对上一节默认成员函数的补充,以及有一个日期类的实现。
赋值运算符重载
赋值运算符重载函数是系统的一个默认成员函数,可以用来进行类对象之间的赋值操作。但系统生成的赋值重载是一种浅拷贝,类中有动态内存的申请时,必须显示定义赋值运算重载。
如下
//赋值运算符重载
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
//赋值重载函数
//传引用返回可以实现连续赋值
//如果不传引用且参数不是const类型,返回的是临时对象具有常性
//当再次调用赋值重载函数时,临时对象传给参数时权限会被放大
//所以传引用减少临时对象拷贝消耗的内存,形参用const限制
Date& operator=(const Date& d)
{
//防止自己对自己赋值
if (this != &d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
//前置++重载
//Date& operator++();
//后置++重载 int可以是任意整型
//Date& operator++(int);
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2025,3,17);
Date d2(2026,6,16);
d1.Print();
d2.Print();
Date d3;
//连续赋值
/*d3 = d2 = d1;
d1.Print();
d2.Print();
d3.Print();*/
////系统也会自动生成赋值重载函数
//d1 = d2;
//d1.Print();
//d2.Print();
//赋值重载函数和拷贝构造函数的比较
//d4未被初始化----拷贝构造
Date d4(d1);
Date d5 = d1;
d4.Print();
d5.Print();
//d6被初始化后再拷贝赋值重载函数
Date d6(1, 1, 1);
d6.Print();
d6 = d1;
d6.Print();
//前置++和后置++
return 0;
}
const成员函数
const修饰的成员函数,const要放在函数声明后面。实际上是修饰函数形参,让this指针指向的内容无法被改变。
如下
//const成员函数
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
//隐式传了一个this指针 类型为Date* const this
//void Print(Date* const this)
//这里的const实际上是修饰的是形式参数 即const Date* const this
//表示this指针指向的类型中的成员不能被修改
void Print() const
/*void Print()*/
{
cout << _year << " " << _month << " " << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
//未被const修饰的类类型传过去是一种权限缩小
d1.Print();
/*const修饰的类类型传过去是一种权限平移*/
const Date d2(2025,3,20);
d2.Print();
//const修饰的类类型传过去,如果函数未被const修饰,权限缩小,程序报错
const Date d3(2025, 3, 21);
d3.Print();
return 0;
}
取地址运算符重载
分为普通&重载和const修饰的重载。这也是系统默认生成的成员函数,我们只需要知道即可。
日期类实现
目的是给之前学的内容做一个练习。
3.17_类和对象_日期类 · 楷哥/116-c++ - 码云 - 开源中国
今天的分享就到此为止了,看没看懂都点个赞呗。