Overloading Operator

I need to compare objects in a program. I need to provide the operator overloading for the operator ">" so that Pokemon can be compared based on its instance variable name and the non-decreasing order of Pokemon objects is defined as the dictionary order of its instance variable name. I hope I described that correctly and it makes sense. I have never done this before and I am confused on how I do the overloading operator. Any help would be greatly appreciated! Here is the Pokemon.h, and Pokemon.cpp programs...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#ifndef POKEMON_H
#define POKEMON_H

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Pokemon
{
   public:
    Pokemon();   //default constructor
    Pokemon(long weight, string name);
    long get_weight() const;
    string get_name() const;
    friend bool operator>(Pokemon pok1, Pokemon pok2);
    friend ostream &operator<<(ostream &out, const Pokemon &pok);

   private:
    long weight;   // the popularity of the pokemon character
    string name;   // the name of the pokemon character
};


#endif  /* POKEMON_H */



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

#include "Pokemon.h"

Pokemon::Pokemon()
{
    weight = 0;
}

Pokemon::Pokemon(long weight, string name)
{
    if (weight < 0)
    {
        cout << "Invalid Popularity! Reset to 0." << endl;
        weight = 0;
    }
    else
        this->weight = weight;
    this->name = name;
}

long Pokemon::get_weight() const
{
    return weight;
}

string Pokemon::get_name() const
{
    return name;
}

closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
    Pokemon poke_1(10,"Pi"), poke_2(10, "Pa");
    
    cout << poke_1.get_name() << '\n';
    
    if(poke_1 > poke_2)
        cout << "True";
    else
        cout << "False";
    
    return 0;
}


.h
friend bool operator>(Pokemon, Pokemon);

.cpp
1
2
3
4
bool operator>(Pokemon pok1, Pokemon pok2)
{
    return pok1.get_name() > pok2.get_name();
}
Last edited on
closed account (48T7M4Gy)
http://www.cplusplus.com/forum/general/202825/
Another similar way:

.h
bool operator>(const Pokemon &) const;

.cpp
1
2
3
4
bool Pokemon::operator>(const Pokemon &Poke2) const
{
        return this->name > Poke2.name;
}

Also, to overload the << operator:

.h
 
friend ostream& operator<<(ostream &os, const Pokemon &poke) const;


.cpp
1
2
3
4
ostream& operator<<(ostream &os, const Pokemon &poke) const
{
        return os << poke.name;
}
Last edited on
Topic archived. No new replies allowed.