加号运算符、左移运算符重载

最近在学C++的运算符重载部分,自己尝试将加号运算符和左移运算符结合在一起写了一个小代码。
主要包括以下几个部分
1、Teacher 类
2、Student 类
3、将 Student 类放在 Teacher 类下,定义一个学生类数组。
4、用左移运算符输出老师及其学生信息、用加号运算符计算学生总分。
5、我是想直接访问私有成员,因此,上述两个函数我都是全局函数,然后加上friend关键字,以全局函数做友元。
代码如下:

#include <iostream>
#include <string>

using namespace std;

class Student
{
    friend ostream &operator<<(ostream &cout, Student student);
    friend int operator+(Student stu1, Student stu2);
public:
    void setName()
    {
        cin >> m_name;
    }
    string getName()
    {
        return m_name;
    }

    void setScore()
    {
        cin >> m_score;
    }

    int getScore()
    {
        return m_score;
    }

private:
    string m_name;
    int m_score;
};

class Teacher
{
    friend ostream &operator<<(ostream &cout, Teacher teacher);
public:
    void setName()
    {
        cout << "name:";
        cin >> m_name;
    }

    string getName()
    {
        return m_name;
    }

    void setStuNum(int stuNum)
    {
        m_stuNum = stuNum;
    }

    void setStuInfo()
    {
        for(int i=0; i<m_stuNum; i++)
        {
            cout << "第" << i+1 << "位学生:" << endl;
            cout << "student name :";
            m_stu[i].setName();
            cout << "student socre:";
            m_stu[i].setScore();
        }
    }

    Student getStuInfo(int index)
    {
        return m_stu[index];
    }

private:
    Student m_stu[2];
    int m_stuNum;
    string m_name;
};

ostream &operator<<(ostream &cout, Student student)
{
    cout << "name :" << student.m_name << endl;
    cout << "score:" << student.m_score;
    return cout;
}

ostream &operator<<(ostream &cout, Teacher teacher)
{
    cout << "name:" << teacher.m_name << endl;
    cout << "student:";
    cout << teacher.m_stu[0] << endl;
    cout << teacher.m_stu[1] << endl;
    return cout;
}

int operator+(Student stu1, Student stu2)
{
    int temp;
    temp = stu1.m_score + stu2.m_score;
    return temp;
}
int main(int argc, char **argv)
{
    Teacher teacher1;
    Student stu1, stu2;
    teacher1.setStuNum(2);

    // set Teacher information
    teacher1.setName();
    teacher1.setStuInfo();
    
    // output 
    cout << endl << teacher1 << endl;
    // teacher1.getName();
    stu1 = teacher1.getStuInfo(0);
    stu2 = teacher1.getStuInfo(1);
    cout << stu1 << endl;
    cout << stu2 << endl;

    cout << (stu1 + stu2) << endl;
    return 0;
}

运算效果如下:
首先是输入信息
在这里插入图片描述
然后是输出结果
在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值