Home > OS >  How do I properly overload the << operand to produce the desired results?
How do I properly overload the << operand to produce the desired results?

Time:08-28

https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3294/

I'm following this Leetcode course on Arrays and am trying to follow along using C as they use Java, but I'm struggling to get past this part. I just want to read items from the pokedex array I made.

The initial error I got was:

No operator << matches these operands.
Array.cpp(16,15) operand types are std::ostream << Pokemon

I then tried to overload the << operator as I've seen other people ask on here, but I'm not getting the output I want. When I compile the program as-is, nothing prints.

Can someone explain what I can do to get the desired output?

Cyndaquill is a fire type at level 5

Also, can someone explain, or point me in the direction of someone who can explain, operator overloading in an easy non-verbose way? A lot of what I've seen on StackOverflow has been overly verbose and confusing. Maybe it's because I'm new to C , but still.

Array.cpp

#include <iostream>
#include "Array_Header.hpp"

int main() {
    
    Pokemon pokeDex[15];

    Pokemon Cyndaquill = Pokemon("Cyndaquill", 5, "Fire");
    Pokemon Totodile = Pokemon("Totodile", 5, "Water");
    Pokemon Chikorita = Pokemon("Chikorita", 5, "Grass");

    pokeDex[0] = Cyndaquill;
    pokeDex[1] = Totodile;
    pokeDex[2] = Chikorita;

    std::cout << pokeDex[0];
    std::cout << pokeDex[1];
    std::cout << pokeDex[2];
    std::cout << pokeDex[3];

}

Array_Header.hpp

#include <string>

class Pokemon {

    public:

    //variable declarations
    std::string name;
    int level;
    std::string type;

    //Constructor for the DVD class
    Pokemon(std::string name, int level, std::string type);
    Pokemon() = default;

    //toString function declaration
    std::string toString();

    friend std::ostream& operator<<(std::ostream& os, const Pokemon& obj) 
    { 
        return os;
    };

};

Array_Header.cpp

#include "Array_Header.hpp"

//Constructor Definition
Pokemon::Pokemon(std::string name, int level, std::string type){
    this->type = type;
    this->level = level;
    this->name = name;
};


//toString function definition
std::string Pokemon::toString(){
    return this->name   " is a "   this->type   " type at level "   std::to_string(level)   "\n";
};

CodePudding user response:

Your operator overload for << to print to an std::ostream an object of type Pokemon does nothing but return the os parameter. You need to add the logic for printing inside of here, which would look something like this:

friend std::ostream& operator<<(std::ostream& os, const Pokemon& obj) 
{
    os << obj.toString();
    return os;
};
  • Related