最近在学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;
}
运算效果如下:
首先是输入信息
然后是输出结果