面向对象程序设计4.0 运算符重载

一、温故

我们定义一个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;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值