为实验二中编写的Songer(歌手)类重载“+”、“>”、“==”、前置“++”、后置“++”等运算符,使Song类的功能更丰富。
1. 重载“+”运算符,实现如下功能
例:s1是Songer类的对象,则 s1+100 能够实现将s1的粉丝数加100
- 将“>”运算符重载为成员函数,实现如下功能
例:s1、s2是Songer类的对象,则 s1>s2 能够实现比较s1的粉丝数是否多于s2的粉丝数
- 将“==”运算符重载为友元函数,实现如下功能
例:如s1、s2是Songer类的对象,则 s1==s2 能够实现比较s1的粉丝数是否等于s2的粉丝数
- 将前置“++”运算符重载为成员函数,实现如下功能
例:s1是Songer类的对象,则 ++s1 能够实现将s1的粉丝数加10
- 将后置“++”运算符重载为友元函数,实现如下功能
例:s1是Songer类的对象,则 s1++ 能够实现将s1的粉丝数加10
6.【选做】:重载“<<”运算符,实现如下功能
例:s1是Songer类的对象,则 cout<<s1 能够实现输出s1的信息(姓名、粉丝数)
Songer.h
#ifndef SHIYANWU_SONGER_H
#define SHIYANWU_SONGER_H
#include<iostream>
#include <cstring>
using namespace std;
class Songer {
private:
char name[10];
int fans_count;
static int count;
public:
Songer();
Songer(char name[10],int fans_count);
Songer(Songer &s);
void setFan(int fans_count);
~Songer();
void static ShowCount();
friend void Pk(Songer &s1,Songer &s2);
void disPlay();
void operator+(int num);
bool operator>(Songer &s2);
friend bool operator ==(Songer &s1,Songer &s2);
Songer operator++();
friend Songer operator ++(Songer &s1,int);
friend ostream &operator<<(ostream &,Songer &s1);
};
#endif //SHIYANWU_SONGER_H
Songer.cpp
#include "Songer.h"
int Songer::count=0;
Songer::Songer() {
count++;
}
Songer::Songer(char *n, int fans)
{
strcpy(name,n);
fans_count=fans;
count++;
}
Songer::Songer(Songer &s)
{
strcpy(name,s.name);
fans_count=s.fans_count;
count++;
}
void Songer::setFan(int fans_count)
{
Songer::fans_count=fans_count;
}
Songer::~Songer()
{
}
void Songer::ShowCount()
{
cout<<"当前歌手人数"<<count<<endl;
}
void Pk(Songer &s1,Songer &s2)
{
if(s1.fans_count==s2.fans_count)
{
cout<<s1.name<<"和"<<s2.name<<"粉丝数相同"<<endl;
}else if(s1.fans_count>s2.fans_count)
{
cout<<s1.name<<"战胜"<<s2.name<<endl;
}else
{
cout<<s2.name<<"战胜"<<s1.name<<endl;
}
}
void Songer::disPlay()
{
cout<<name<<" "<<fans_count<<endl;
}
void Songer::operator+(int num)
{
Songer::fans_count+=num;
}
bool Songer::operator>(Songer &s2)
{
if(this->fans_count>s2.fans_count)
return 1;
else
return 0;
}
bool operator==(Songer &s1,Songer &s2)
{
if(s1.fans_count==s2.fans_count)
return true;
else
return false;
}
Songer Songer::operator++()
{
fans_count+=10;
return *this;
}
Songer operator++(Songer&s1,int)
{
Songer temp=s1;
s1.fans_count+=10;
return temp;
}
ostream & operator<<(ostream & co,Songer &s1)
{
cout<<"姓名:"<<s1.name<<" 粉丝数:"<<s1.fans_count;
return co;
}
main.cpp
#include"Songer.h"
using namespace std;
int main() {
Songer songer1((char*)"张三",100);
Songer songer2((char*)"李四",120);
Songer songer3((char*)"王五",90);
cout<<"1.重载+"<<endl;
songer1.disPlay();
songer1+100;
songer1.disPlay();
cout<<"2.重载>"<<endl;
if(songer1>songer2)
cout<<"true"<<endl;
else
cout<<"false"<<endl;
cout<<"3.重载=="<<endl;
if(songer1==songer2)
cout<<"true"<<endl;
else
cout<<"false"<<endl;
cout<<"4.重载前置++"<<endl;
songer1.disPlay();
++songer1;
songer1.disPlay();
cout<<"5.重载后置++"<<endl;
songer2.disPlay();
songer2++;
songer2.disPlay();
cout<<"6.重载<<"<<endl;
cout<<songer1;
}