1.成员函数重载
2.全局函数重载
3.输出运算符重载
4.拷贝赋值运算符
5.移动赋值运算符
#include <iostream>
#include <string>
using namespace std;
class stu{
public:
string name;
int age;
stu(int age):age(age){
cout << "有参构造stu"<< endl;
}
stu(string name,int age):name(name),age(age){
cout << "有参构造2stu"<< endl;
}
stu operator+(stu &s){
return (this->age + s.age);
}
};
class teacher{
public:
string name;
int age;
teacher(int age):age(age){
cout << "有参构造1"<< endl;
}
teacher(string name,int age):name(name),age(age){
cout << "有参构造2"<< endl;
}
};
teacher operator+ (teacher & te,teacher & t){
return (te.age + t.age);
}
class school{
public:
string name{"希望小学"};
school(string name){
this->name = name;
}
};
ostream& operator<<(ostream& o,school& s){
o << s.name;
return o;
}
class hospital{
public:
string address;
hospital(){
cout << "hostpital无参构造"<< endl;
}
};
istream& operator>>(istream &in,hospital &h){
in >> h.address;
return in;
}
class hotel{
public:
string name;
int price;
hotel& operator=(const hotel &p){
cout << "执行拷贝赋值函数"<< endl;
this->name = p.name;
this->price = p.price;
return *this;
}
};
class doctor{
public:
string name;
int age;
doctor& operator=(doctor && d){
cout << "调用移动赋值运算函数"<< endl;
if(this != &d){
this->name = move(d.name);
d.name = " ";
this->age = move(d.age);
d.age = 0;
}
return *this;
}
};
int main() {
stu s1("小明",12);
stu s2("小红",13);
stu s3 = s1 + s2;
cout << s3.age << endl;
teacher t1("夏老师",30);
teacher t2("王老师",32);
teacher t3 = t1 + t2;
cout << t3.age << endl;
school sc("希望中学");
cout << sc << endl;
hospital h;
cin >> h;
cout << h.address << endl;
hotel p;
p.name = "京基酒店";
p.price = 100;
hotel p2;
p2 = p;
doctor d;
d.name = "牙博士";
d.age = 18;
doctor d2;
d2 = move(d);
return 0;
}