运算符重载
运算符重载本质
重新定义运算符的操作,返回自定义的结果。
对于A operator sign (B res1 , C res2)
B类型的res1和C类型的res2,进行sign操作,返回一个类型是A的结果。
1. 一元运算符重载
(1)重载++
class student
{
public:
int a;
student(int a)
{
this->a = a;
}
student operator ++ ()
{
++a;
return student(a);
}
};
int main()
{
student a(3);
++a;
cout<<a.a;
return 0;
}
(2)重载-(负号)
class student
{
public:
int a;
student(int a)
{
this->a = a;
}
student operator - ()
{
return student(-a);
}
};
int main()
{
student a(3);
cout<<-a.a;
return 0;
}
2. 二元运算符重载(+)
class student
{
public:
int a;
student(int a)
{
this->a = a;
}
student operator + (student res)
{
return student(a+res.a);
}
};
int main()
{
student res1(3),res2(4);
cout<<(res1+res2).a;
return 0;
}
3. 关系运算符重载(<)
struct student
{
int a;
bool operator < (student x)
{
return a<x.a;
}
};
4. 输入输出运算符重载
class student
{
public:
int a,b;
// student(int a,int b)
// {
// this->a = a;this->b = b;
// }
friend ostream &operator << (ostream &output,student &s)
{
output<<s.a<<" "<<s.b;
return output;
}
friend istream &operator >> (istream &input , student &s)
{
input>>s.a>>s.b;
return input;
}
};
int main()
{
student a;
cin>>a;
cout<<a;
return 0;
}
5. 赋值运算符重载(=)
class student
{
public:
int a,b;
student(int a,int b)
{
this->a = a;this->b = b;
}
void operator = (student res)
{
a = res.a;b = res.b;
}
};
int main()
{
student a(3,2),b(2,3);
a = b;
cout<<a.a<<" "<<a.b;
return 0;
}
6. 下标运算符重载
class student
{
public:
int a,b;
int arr[100];
student(int a,int b)
{
this->a = a;this->b = b;
}
int operator [] (int i)
{
return arr[i];
}
};
int main()
{
student a(3,2);
a.arr[3] = 2;
cout<<a[3];
return 0;
}