赋值运算符
- 赋值运算符重载用于对象数据的复制
- operator= 必须重载为成员函数
重载函数原型为:
类型 & 类名 :: operator= ( const 类名 & ) ;
#include <iostream>
#include <string.h>
using namespace std;
class Student
{
friend ostream &operator<<(ostream &out, const Student &s);
private: // 一般 拷贝构造 赋值运算符重载都应该写成私有的 声明即可,不需实现
// Student (const Student &obj);
// Student &operator=(const Student &s);
public:
Student()
{
}
Student (int age, char *name)
{
this->age = age;
this->name = name;
}
private:
int age;
char *name;
};
ostream &operator<<(ostream &out, const Student &s)
{
printf ("age = %d, name = %s", s.age, s.name);
return out;
}
int main()
{
Student s(10, "小明");
cout << "s : " << s << endl;
// 拷贝构造,默认拷贝构造
Student s1 = s;
cout << "s1: " << s1 << endl;
Student s2;
// 赋值, 如果没有自己写赋值运算符重载,编译器默认会提供一个赋值运算符重载函数,做一些值的复制
// operator=(s2, s) ==> Student &operator(Student &s1, const Student &s2)
// operator=(s1, s)
// operator=(s2, operator=(s1, s))
// Student &operator=(const Student &s)
s2 = (s1 = s);
cout << "s2: " << s2 << endl;
return 0;
}
执行结果:
s : age = 10,name = 小明
s1: age = 10,name = 小明
s2: age = 10,name = 小明
class Teacher
{
friend ostream &operator<<(ostream &out, const Teacher &s);
public:
Teacher()
{
age = 0;
name = NULL;
}
Teacher (int age, char *name)
{
this->age = age;
this->name = new char[20];
strcpy (this->name, name);
}
Teacher (const Teacher &obj)
{
this->age = obj.age;
this->name = new char[20];
strcpy (this->name, obj.name);
}
~Teacher()
{
if (name != NULL)
delete [] name;
name = NULL;
age = 0;
}
Teacher &operator=(const Teacher &obj)
{
// 函数入口参数检查 如果是自己直接返回
if (&obj == this)
return *this;
// 1、释放原有的空间
if (name != NULL)
delete [] name;
// 2、开辟新空间
this->name = new char[20];
// 复制
this->age = obj.age;
strcpy (this->name, obj.name);
return *this;
}
private:
int age;
char *name;
};
ostream &operator<<(ostream &out, const Teacher &s)
{
printf ("age = %d, name = %s", s.age, s.name);
return out;
}
int main()
{
Teacher t1(20, "wang");
Teacher t2 = t1;
cout << t2 << endl;
Teacher t3(25, "zhang");
// 默认的赋值运算是 一个浅拷贝的过程, 不会复制堆上的空间
t3 = t2;
cout << t3 << endl;
Teacher t4;
t3 = t3;
return 0;
}
执行结果:
age = 20,name = wang
age = 20,name = wang
结论:
1 先释放旧的内存
2 返回一个引用
3 =操作符 从右向左,优先级相同然后看赋值运算符的结合性。
有些人觉得 如果直接写深拷贝,那么赋值运算是否在某种程度上就用不到了,个人觉得在个别情况下可行,但是如果遇到两个对象都初始化过了,那么此时就必须进行赋值操作了,所以还是有必要的
622

被折叠的 条评论
为什么被折叠?



