一、温故
我们定义一个Student类
class Student
{
string name;
int id;
public:
Student(){}
Student(string name,int id)
{
this->name=name;
this->id=id
}
};
二、知新
<<和>>的重载
假设我们在这里定义并初始化了一个整型变量 int a=10;
可以用cout<<a来实现a的输出。
为了实现cout<<一个学生类的对象,我们可以对<<进行运算符重载
在这里一般用友元的方法实现。
#include <iostream>
#include <string>
using namespace std;
class Student
{
string name;
int id;
public:
Student(){}
Student(string name,int id)
{
this->name=name;
this->id=id;
}
friend ostream &operator<<(ostream &q,const Student &s);
};
ostream &operator<<(ostream &q,const Student &s)
{
cout<<s.name<<s.id<<endl;
return q;
}
int main()
{
Student stu1("stu1",1),stu2("stu2",2);
cout<<stu1<<endl<<stu2<<endl;
return 0;
}
把写好的程序运行一下,emmmm,输出如下:

达到了理想输出
我们继续。
普通运算符
我们对学生类稍作修改。
class Student
{
string name;
int score;
public:
Student(){}
Student(string name,int score)
{
this->name=name;
this->score=score;
}
friend ostream &operator<<(ostream &q,const Student &s);
};
假设这里有50个学生,我们想找出成绩最高的那个,于是我们需要对“>"运算符进行重载
bool operator >(const Student &s)
{
if(this->score>s.score) return true;
else return false;
}
注意返回值,是bool类型的。
然后是++运算符,有前置和后置的区分
假设这个时候 ,学生stu1发现老师改错了,把这改错的一分加上,为了方便,我们希望用stu1++的形式,让stu1的分数加上.
//front
Student &operator++()
{
score++;
return *this;
}
//back
Student operator++(int)
{
Student temp=*this;
score++;
return temp;
}
这里会区分前置++与后置++的区别。
int a=b++;
执行顺序为:a=b→b+=1;
int a=++b;
执行顺序为:b+=1→a=b;
前置与后置的区别是后置的运算符重载里有(int)作为区分。
然后是等号运算符。
在前面我们提过:
Student stu1=stu2是正确的,
Student stu1;
stu1=stu2;
就是不正确的。
我们需要对“=”运算符重载。
Student &operator=(const Student &t )
{
this->name=t.name;
this->score=t.score;
}
剩下有几个运算符是不能重载的相信大家都清楚,这里只提一句。
三、练练手
创建一个Student类型 的数组,对它按以下方式初始化并按成绩从小到大的顺序排序。
Student stu[10];
for(int i=0;i<10;i++)
{
string s="Student";
s+=to_string(i+1);
s+=" ";
Student stu_temp(s,rand()%100);
stu[i]=stu_temp;
cout<<stu[i]<<endl;
}
283

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



