运算符重载其实就是一种 “语法上的方便” , 背后实际上是一种函数调用的方式, 调用的是重载的函数
如 ,两个对象进行相加,一般情况下是不允许的, 但,通过运算符重载将 + 号替换为调用类中的函数就可以做到看上去的类相加了, 如:
class stu{
int money;
string name;
public:
stu(string name, int money){
this->name = name;
this->money = money;
}
int operator+(stu &s){
return this->money / s.money;
}
};
int main() {
stu s1("laowang", 100);
stu s2("laoli", 10);
cout << "两个对象的零钱的和是: " << s2 + s1 << endl;
return 0;
}
运算符重载就是调用对象中的函数实现类中的某个属性之间的相加
成员函数
把重载的运算符函数定义在类中,此时只需要接收一个参数,因为类的对象本身作为+
的前面调用者。
全局函数
一些需要其他类的运算符就不能在类中定义了,如:cin >>
和cout <<
需要 cin 或 cout 类,因为ostream类已经被封装好了。 ,所以,要在类外部定义,传递cout 对象,和 要操作的类
istream& operator>> (istream& c, stu &s){
cout << "请输入学生的名字: " << endl;
string names;
c >> names;
s.name = new string(names);
cout << "请输入学生的学号: " << endl;
c >> s.stu_num;
return c;
};
如果不是链接调用,则不需要返回值,(链接调用: cout << “aa” << “bb” << endl;)
拷贝赋值运算
拷贝复制跟拷贝构造差不多,多少重原对象中拷贝数据到新对象上, 拷贝赋值运算 就是将 = 重载,
//拷贝赋值
Stu& operator=(const Stu &s){
this->name = s.name;
return *this
}
移动赋值运算
移动赋值运算和移动构造差不多,将原对象中的指针类型的数据给新对象, 然后将原对象的指针设置为nullptr
//移动赋值
Stu& operator=(const Stu &&s){
cout <<"执行移动赋值函数" << endl;
d = s.d;
h.d = nullptr;
return *this;
}