C++ - Overloaded Operator in Derived Class not working - c++

Okay, so the overloaded operator for the derived class is not working. It is only using the overloaded operator in the base class. Any ideas why?
Base class operator in class definition header file:
friend ostream & operator << (ostream & out, const PocketMonster & p);
Base class operator:
ostream & operator << (ostream & out, const PocketMonster & p)
{
out << endl << "(Monster Types: Type 1 = Fire, Type 2 = Water, Type 3 = Grass)" << endl
<< "PocketMonster Information: " << endl << "Name: " << p.name << endl
<< "Status (0=Dead, 1=Alive): " << p.status << endl << "Level: " << p.level << endl
<< "Strength: " << p.strength << endl
<< endl << "(Weapon Types: 1 = Fire, 2 = Water, 3 = Grass, 4 = Normal)" << endl
<< p.name << "'s Weapon Information: " << endl << "Weapon type: " << p.get_weaptype() << endl
<< "Weapon durability: " << p.get_weapdura() << endl << "Weapon level required: " << p.get_weaplvl() << endl << endl;
return out;
}
Derived class overloaded operator in class definition header file:
friend ostream & operator << (ostream & out, const FireMonster & p);
Derived class overloaded operator:
ostream & operator << (ostream & out, const FireMonster & p)
{
return out << static_cast<const PocketMonster&>(p) << endl << "FireMonster Attributes:" << endl << "Temperature: " << p.temperature << endl;
}
And here's a function where it tries to output the information
void displayLosers(vector<PocketMonster *> p)
{
for (int i=0; i<p.size(); i++)
{
if (p[i]->get_status() == false)
{
cout << p[i]->get_name() << " is a loser." << endl;
cout << *(p[i]);
}
}
}
Thanks for help in advance!

Add virtual function Output to the base class (at public or protected section):
virtual ostream & Output (ostream & out) const;
// ...
ostream & PocketMonster::Output (ostream & out) const
{
out << endl << "(Monster Types: Type 1 = Fire, Type 2 = Water, Type 3 = Grass)" << endl
<< "PocketMonster Information: " << endl << "Name: " << p.name << endl
<< "Status (0=Dead, 1=Alive): " << p.status << endl << "Level: " << p.level << endl
<< "Strength: " << p.strength << endl
<< endl << "(Weapon Types: 1 = Fire, 2 = Water, 3 = Grass, 4 = Normal)" << endl
<< p.name << "'s Weapon Information: " << endl << "Weapon type: " << p.get_weaptype() << endl
<< "Weapon durability: " << p.get_weapdura() << endl << "Weapon level required: " << p.get_weaplvl() << endl << endl;
return out;
}
and override it in derived class:
virtual ostream & Output (ostream & out) const;
// ...
ostream & FireMonster::Output (ostream & out) const
{
return out << PocketMonster::Output(out) << endl << "FireMonster Attributes:" << endl << "Temperature: " << p.temperature << endl;
}
Then rewrite operator<< for the base class in the following way:
ostream & operator << (ostream & out, const PocketMonster & p)
{
return p.Output(out);
}
and remove operator<< for derived class.

Related

C++ access object behind iterator in loop

I have created a list of objects of a class.
The class has an overloaded ostream << operator to output customer data in a structured way.
What I am trying to do is loop over the list of objects and call cout on the object in the iteration.
Code for the loop is as follows:
for (list<Kunde>::iterator it = this->kun_list.begin(); it != this->kun_list.end(); ++it) {
cout << it << endl;
}
With Kunde being the class with the overloaded << operator and kun_list being the list of objects of type Kunde.
friendly overload within the Kunde class:
friend ostream& operator<< (ostream& os, Kunde& kd) {
os << "__Kundendaten__" << endl;
os << "Name: " << kd.vorname << " " << kd.name << endl;
os << "Geburtsjahr: "<< kd.geburtsjahr << endl;
os << "Adresse: " << kd.strasse << " " << kd.hausnummer << endl << kd.plz << " " << kd.ort << endl;
os << "Telefon: " << kd.telefonnummer << endl;
string fschein = "Nein.";
if (kd.klasse_a_vorhanden) {fschein = "Ja.";}
os << "Führerschein Kl. A vorhanden: " << fschein << endl;
return os;
};
The above loop does not work because I am using the list iterator instead of an object of class Kunde. I can access members of Kunde via it→member but how do I use that iterator as reference to the whole object?
Thanks!
Use a const reference loop over the container:
for (const auto & kunde : kun_list) {
cout << kunde << endl;
}
Obviously you also have to fix <<:
friend ostream& operator<< (ostream& os, const Kunde& kd) {...}

C++ "Class Enum" Novice Problems

I'm starting learning to code in C++ (coming from VB.net) and i need some help in enum class usage.
I've done this simple code from a lerning exercise (originally divided in header.h and Exercise.cpp, but i putted it all together here):
#include <iostream>
#include <string>
#define BEGIN_WITH(x) { \
auto &_ = x;
#define END_WITH() }
using namespace std;
enum class Gender { Male, Female };
struct PersonStruct {
string _Name;
string _SurName;
int _Age;
double _Heigth;
Gender _Gender; };
class Person { public:
string _Name{};
string _SurName{};
int _Age{};
double _Heigth{};
Gender _Gender{}; };
int ModifyPerson(Person& PassPersona, PersonStruct Attribute) {
PassPersona._Name = Attribute._Name;
PassPersona._SurName = Attribute._SurName;
PassPersona._Heigth = Attribute._Heigth;
PassPersona._Age = Attribute._Age;
PassPersona._Gender = Attribute._Gender;
return(0); }
int main() { Person TestingPerson;
BEGIN_WITH(TestingPerson)
_._Age = 23;
_._Gender = Gender::Male;
_._Heigth = 1.94;
_._Name = "John";
_._SurName = "Smith";
END_WITH()
cout << "Person attributes: " << endl;
cout << "Name: " << TestingPerson._Name << endl;
cout << "Surname: " << TestingPerson._SurName << endl;
cout << "Age: " << TestingPerson._Age << endl;
cout << "Gender: " << TestingPerson._Gender << endl;
cout << "Heigth: " << TestingPerson._Heigth << endl;
cout << endl;
ModifyPerson(TestingPerson, PersonStruct{ "Poca","Hontas",24,1.85,Gender::Female });
cout << "New Person attributes: " << endl;
cout << "Name: " << TestingPerson._Name << endl;
cout << "Surname: " << TestingPerson._SurName << endl;
cout << "Age: " << TestingPerson._Age << endl;
cout << "Gender: " << TestingPerson._Gender << endl;
cout << "Heigth: " << TestingPerson._Heigth << endl;
return(0); }
I've made the structure in order to group all Person class parameters. Doing this i've learned that using enum class is more secure than class. But when i switched to enum class a lot of errors prompted on my code. I've solved almost all of them, except this:
cout << "Gender: " << TestingPerson._Gender << endl;
Error code E0349 "no operator "<<" matches these operands"
I've searched around but i find no solution to this. Thanks in advance for your time! (any suggestion or recommendation on my code should be appreciated)
<< operator is not defined for class Gender because it's your own class. You'll need to overload it. More info here.
enum class Gender
{
male,
female
};
ostream& operator<< (ostream & os, const Gender & g)
{
switch(g)
{
case Gender::male: os << "Male"; return os;
case Gender::female: os << "Female"; return os;
}
return os;
};

C++ proper usage of ostream inside a class and passing arguments?

I've recently started learning c++ and for the life of me, I can't seem to get the syntax of using ostream in a class and what arguments should I pass. Here's the code:
This is the class in question:
#include <iostream>
#include <string>
using namespace std;
class Pokemon{
friend ostream& operator<<(ostream&, Pokemon);
public:
string name, level, cp;
Pokemon(string x="Pikachu", string y="5", string z="1000"){
name = x;
level = y;
cp = z;
}
Pokemon name(){
return this->name;
}
Pokemon level(){
return this->level;
}
Pokemon cp(){
return this->cp;
}
Pokemon display_stats(){
cout << this-> name << "stats are:" << endl;
cout << " " << "Attack: 2716.05" << endl;
cout << " " << "Defence: 1629.63" << endl;
cout << " " << "HP: 1086.42" << endl;
}
};
template<typename TYPE> //i dont understand this and the things i've written down here are only based on samples i've seen
ostream& operator<<(ostream& os, Pokemon & c){
os << "The level of " << c.name << " is" << c.level << " with cp of " << c.cp;
}
As you could see, I already tried constructing the ostream thing but I don't really understand how it works. This is my main function:
int main()
{
Pokemon a, b, c, d;
a = Pokemon();
b = Pokemon("Weezing");
c = Pokemon("Nidoking", 100);
d = Pokemon("Mewtwo", 50, 5432.1);
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
cout << "Jessie: You are no match to me! Go " << b.name << "!" << endl;
cout << "Gary: Go lvl " << c.level << " " << c.name << "! Crush them" << endl;
cout << "Ash: " << a.name << " can do it even thouh he is only level " << a.level << endl;
cout << "Jessie: Hahaha! My " << b.name << " CP is " << b.cp << endl;
cout << "Gary: "<< c.name << " CP is " << c.cp << endl;
cout << "Ash: " << a.name << " CP is " << a.cp << endl;
cout << "Giovanni: Behold " << d.name << " is here." << endl;
d.display_stats();
return 0;
}
I'm getting errors of:
no instance of constructor "Pokemon::Pokemon" matches the argument list -- argument types are: (const char [9], int) //on line c = Pokemon("Nidoking", 100);
no instance of constructor "Pokemon::Pokemon" matches the argument list -- argument types are: (const char [7], int, double) //on line d = Pokemon("Mewtwo", 50, 5432.1);
All of your Pokemon class methods are returning the wrong type. And your main() is not calling any of the methods correctly at all.
Change your Pokemon class to look more like this:
#include <iostream>
#include <string>
using namespace std;
class Pokemon {
private:
string m_name;
int m_level;
double m_cp;
friend ostream& operator<<(ostream&, const Pokemon&);
public:
Pokemon(string x="Pikachu", int y=5, double z=1000) {
m_name = x;
m_level = y;
m_cp = z;
}
string name() const {
return m_name;
}
int level() const {
return m_level;
}
double cp() const {
return m_cp;
}
void display_stats() const {
cout << m_name << " stats are:" << endl;
cout << " " << "Attack: 2716.05" << endl;
cout << " " << "Defense: 1629.63" << endl;
cout << " " << "HP: 1086.42" << endl;
}
};
ostream& operator<<(ostream& os, const Pokemon &c) {
os << "The level of " << c.m_name << " is " << c.m_level << " with cp of " << c.m_cp;
return os;
}
And then change main() to look more like this:
int main()
{
Pokemon a;
Pokemon b("Weezing");
Pokemon c("Nidoking", 100);
Pokemon d("Mewtwo", 50, 5432.1);
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
cout << "Jessie: You are no match to me! Go " << b.name() << "!" << endl;
cout << "Gary: Go lvl " << c.level() << " " << c.name() << "! Crush them" << endl;
cout << "Ash: " << a.name() << " can do it even though he is only level " << a.level() << endl;
cout << "Jessie: Hahaha! My " << b.name() << " CP is " << b.cp() << endl;
cout << "Gary: " << c.name() << " CP is " << c.cp() << endl;
cout << "Ash: " << a.name() << " CP is " << a.cp() << endl;
cout << "Giovanni: Behold " << d.name() << " is here." << endl;
d.display_stats();
return 0;
}
Live Demo

Need Help Operator Overloading So I Can Display Functions

I'm stuck trying to figure out how to overload the << operator so I can display my rational class functions.
These are the lines I'm trying to overload:
cout << "Testing the compare() member function, found:" << endl;
if (r1.compare(r2) == 1)
cout << r1.display() << " is greater than " << r2.display() << endl;
else if (r1.compare(r2) == 0)
cout << r1.display() << " is equal to " << r2.display() << endl;
else if (r1.compare(r2) == -1)
cout << r1.display() << " is less than " << r2.display() << endl;
cout << "Testing the four arithmetic member functions:" << endl;
cout << "r1 + r2 = " << r1.display() << " + " << r2.display() << " = " << r1.add(r2) << endl;
cout << "r1 - r2 = " << r1.display() << " - " << r2.display() << " = " << r1.subtract(r2) << endl;
cout << "r1 * r2 = " << r1.display() << " * " << r2.display() << " = " << r1.multiply(r2) << endl;
cout << "r1 / r2 = " << r1.display() << " / " << r2.display() << " = " << r1.divide(r2) << endl;
The errors occur everytime I call a function. Here is the code for the functions:
void rational::display()
{
int gcd = GCD();
if (denom < 0)
{
num = -num;
cout << num / gcd << " / " << denom / gcd << endl;
}
else if (num == 0)
cout << num << endl;
}
rational rational::add(const rational &r2) const
{
rational sum;
sum.num = (num * r2.denom) + (r2.num * denom);
sum.denom = denom * r2.denom;
return sum;
}
The multiply, divide, and subtract functions are as same as the add they just have the symbols and variable name changed to match the operation. My overload operator is set up like this:
ostream& operator<< (ostream& out, rational &robj)
{
out << example code << example code;
return out;
}
Any help would be appreciated. This is my first time posting so if I need to post more of my code I will. Thanks!
First of all, change
ostream& operator<< (ostream& out, rational &robj)
to
ostream& operator<< (ostream& out, rational const& robj)
Then, instead of
cout << r1.display() << " is greater than " << r2.display() << endl;
use
cout << r1 << " is greater than " << r2 << endl;
Since you already have the above operator<< function, I would get rid of the member function display(). It doesn't (should not) give you any more functionality than using the operator<< function.
Given
rational 1
Use of
r.display();
should give you the same output as
cout << r << endl;
See What are the basic rules and idioms for operator overloading? for more details on operator overloading.

OOP: Method for cout output

I have to create a method, which prints all collected data's on screen, here is my try:
bool UnPackedFood::printer() {
cout << " -- Unpacked Products --" << endl;
cout << "barcode: " << getBarcode() << endl;
cout << "product name: " << getBezeichnung() << endl << endl;
cout << "weight: " << getGewicht() << endl;
cout << "price" << getKilopreis() << endl;
return true;
}
In my main:
UnPackedFood upf;
cout << upf.printer();
This shows me the correct output, but it still delivers me a bool value back, which I actually dont need. I tried to declare the method as void, but thats not working.
You should overload << operator for output stream. Then when you type cout << upf it will print your product.
Take a look at this example and try to do something similar to following snippet:
class UnPackedFood {
...
public:
...
friend ostream & operator<< (ostream &out, const UnPackedFood &p);
};
ostream & operator<< (ostream &out, const UnPackedFood &p) {
out << " -- Unpacked Products --" << endl;
out << "barcode: " << p.getBarcode() << endl;
out << "product name: " << p.getBezeichnung() << endl << endl;
out << "weight: " << p.getGewicht() << endl;
out << "price" << p.getKilopreis() << endl;
return out;
}
Three possible solutions:
Don't do cout << upf.printer();, the output is not needed since the function itself does the output.
Instead of writing to the output in the printer function, append to a string and return the string.
Make an overloaded operator<< for UnPackedFood, so you can just do std::cout << upf;