0

I am trying to overload the operator << to display contents on the object, but I need it in a few different classes so I make the operator << and showStatus() function templates.

IDE shows the following error:

Undefined symbol: operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, Mege const&)

Not sure about what it is.

I delete some unrelated code so this question will not be too much code to be posted. Let me know if more details are needed.

Help would be appreciated.

class Hero : public Entity{
private:
public:
    template <class T>
    void showStatus(T){}
};
#include "Hero.hpp"
#include <math.h>

Hero::Hero(){

}

//  overloading << for showing different hero's status
template <class T>
std::ostream &operator << (std::ostream &strm, const T &hero){
    strm << hero.getName() << endl
         << "-------------------------------"
         << "Level: "       << right << setw(4) << hero.getLevel() << endl
         << "EXP: "         << hero.getExp()        << " / " << hero.getExpNext()   << endl
         << "HP: "          << hero.getCurrHp()     << " / " << hero.getMaxHp()     << endl
         << "Damage: "      << hero.getMinDamage()  << " ~ " <<hero.getMaxDamage()  << endl
         << "-------------------------------"
         << "Strength: "    << hero.getStrength()       << endl
         << "Intelligence: "<< hero.getInterlligence()  << endl
         << "Stamina: "     << hero.getStamina()        << endl
         << "Speed: "       << hero.getSpeed()          << endl
         << "-------------------------------"   << endl << endl;
    return strm;
}
#include <stdio.h>
#include <iostream>
#include "Hero.hpp"
class Mege : public Hero{
private:
public:
    Mege();
    ~Mege();
    //  function
    friend std::ostream &operator << (std::ostream &strm, const Mege &hero);
    void updateStatus() override;
    void showStatus(Mege) ;
    //  setter
    //  getter
};
#include "Mege.hpp"
#include <math.h>

std::ostream &operator << (std::ostream &strm, const Mege &mege);
void Mege::showStatus(Mege mege){
    cout << mege;
}

Zhihan L
  • 35
  • 7
  • Unfortunately, your template definition in your `.cpp` file is mostly useless, because C++ templates don't work this way. See the linked question for more information. Furthermore, even when that's fixed, `T` can be /any/ type, there's nothing in the template that requires it to be a subclass of `Hero`, as such it'll always participate in overload resolution, potentially resulting in mind-bending error messages that C++ compilers are famous for. – Sam Varshavchik Apr 18 '20 at 03:40
  • @SamVarshavchik so that's said, should I just give up using templates ? then overload << on each class where need it? – Zhihan L Apr 18 '20 at 03:52
  • A template function may or may not the best solution here, this is something that you need to decide for yourself; since this would mostly be opinion, and opinions are off-topic here. – Sam Varshavchik Apr 18 '20 at 03:56

0 Answers0