以下代码重载了运算符+= 和 -=,使代码能够在自定义的YouTubeChannel list中增减对象。
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
struct YouTubeChannel{
string Name;
int SubscribersCount;
YouTubeChannel(string name, int subscribersCount){
Name = name;
SubscribersCount = subscribersCount;
}
bool operator==(const YouTubeChannel & channel){
return this->Name == channel.Name;
}
};
struct MyCollection{
list<YouTubeChannel> myChannels;
void operator+=(YouTubeChannel & channel){
this->myChannels.push_back(channel);
}
void operator-=(YouTubeChannel & channel){
this->myChannels.remove(channel);
}
};
ostream& operator<<(ostream& COUT, YouTubeChannel& ytChannel){
COUT << "Name: " << ytChannel.Name << endl;
COUT << "SubscribersCount: " << ytChannel.SubscribersCount << endl;
return COUT;
}
ostream& operator<<(ostream& COUT, MyCollection& myCollection){
for(YouTubeChannel ytChannel: myCollection.myChannels){
COUT << ytChannel << endl;
}
return COUT;
}
int main(){
YouTubeChannel yt1 = YouTubeChannel("dell", 5000);
YouTubeChannel yt2 = YouTubeChannel("asus", 7000);
MyCollection myCollection;
myCollection += yt1;
myCollection += yt2;
myCollection -= yt2;
cout << myCollection;
return 0;
}