C++[类和对象][3]
赋值运算符的重载(operator=)
1.是一个默认成员函数,重载必须为成员函数,用于两个已经存在的对象,(d1=d3赋值重载)(Stack d4=d1拷贝构造(因为d4未存在,初始化))
2.建议写成引用返回提高效率,可以连续赋值重载
3.没有写的时候会自动生成,完成值拷贝/浅拷贝对(对于自定义类型)(一个修改会修改另一个)
4.栈实现赋值重载,要先销毁空间,创建一个一样的空间,再拷贝
class Date
{
public:
Date(int year=1,int month=1,int day=1)
{
_year=year;
_month=month;
_day=day;
}
Date(const Date& d)//(拷贝构造,把d1传参给d)引用传参不改变使用const
//注意使用&,不然会无穷递归(传值传参函数返回都规定要调用拷贝构造)
{
_year=d.year;
_month=d.month;
_day=d.day;
}
Date& operator=(const Date& d)//
{
if(this!=&d)
{
_year=d.year;
_month=d.month;
_day=d.day;
}
return *this;//(添加this指针的引用返回可以连续赋值)
}
void Print()
{
cout<<_year<</<<_month<</<<_day<<endl;
}
private:
{
int _year=year;
int _month=month;
int _day=day;
}
class Stack
{
public:
Stack& operator=(const Stack& st)
{//先判断
if(this!=&st)
{
free(a);
a=(int*)malloc(sizeof(int)*st.capcity);
if(a==nullptr)
{
perror("malloc fail!");
return;
}
memcpy(a,st.a,sizeof(int)*st.top);
top=st.top;
capcity=st.capcity;
}
return *this;//栈的赋值重载
}
private:
int top;
int capcity;
}
};
int main()
{
Date d1(2025,4,24);
Date d2(d1);
Date d3;
d3=d1=d2;//赋值重载
Stack st1;
Stack st2;
st1=st2;
}