overloading

Hello guys I am trying to overload [] i want to do this
Pokemon somePok;
somePok[new Pokemon{ "PIKACHU", 100 },
new Pokemon{ "CHARMANDER", 100 }];
and I have put this in class pokemon
Pokemon* &operator[] (Pokemon*);/*inside pokemon class*/
when pokemon class ends I have put this
Pokemon* &Pokemon::operator[](Pokemon*first)
{

return first;
}
but when i put something like this
somePok[new Trainer{ "ASH" },
new Pokemon{ "CHARMANDER", 100 }];
it passes compile and creates everything but when i do this
somePok[new Pokemon{ "PIKACHU", 100 },
new Trainer{ "ASH", 100 }];
it hits error in compiler
how can i fix this?
You can't overload operator[] to accept multiple arguments.
https://stackoverflow.com/questions/1936399/c-array-operator-with-multiple-arguments
https://www.geeksforgeeks.org/overloading-subscript-or-array-index-operator-in-c/

Though I can't even tell if that's what you're trying to do. No one knows what you're trying to do. We gave a friendly hint in the other thread that you're just abusing the language.
Last edited on
and how can I see if all object are Pokemons?
I'm flattered that you think I'm psychic, but I don't know what you're talking about.
Is a Trainer a Pokemon, or is a Pokemon a Trainer? Or are both Pokemon and Trainer subclasses of something?
The answer might be dynamic_cast, but generally that should be avoided, and you should use virtual calls instead. (Or perhaps avoid polymorphism and don't put Trainers in the same array as Pokemon)

https://www.bogotobogo.com/cplusplus/dynamic_cast.php
https://stackoverflow.com/a/2254183/8690169
Last edited on
No I just have one class Pokemon and one class Trainer nothing else what should I do?
Why do Pokemon and Trainer need to be part of the same array in the first place?
Why not just have an array of Pokemon?
And a Trainer owns ("has-a") an array of Pokemon.
Last edited on
This is not an array and I just dont want this to happen
somePok[new Trainer{ "ASH" },
new Pokemon{ "CHARMANDER", 100 }];
I just want to have only Pokemon object inside of []
Sorry then, I give up.

My preferred design would be:
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
// Example program
#include <iostream>
#include <string>

using namespace std;

class Pokemon {
  public:
    string name;
    int hp;
};


class Trainer {
  public:
   string name;
   Pokemon party[6] = {};
};


int main()
{
    Trainer trainer;
    trainer.name = "Misty";
    
    trainer.party[0] = Pokemon{"Pikachu", 60};
    trainer.party[1] = Pokemon{"Slowpoke", 70};
    // ...
}
Topic archived. No new replies allowed.