Errors with operator overloading - c++

i have two different operator overloading. For some reason it is giving error.
If i remove one of it, than it does not show any error. May i know why ?
Can i combine both ?
This is used for printing on screen.
ostream& operator<<(ostream &out, const Point &p) {
return out << "[" << setw(4) << p.getX() << setw(1) << "," << setw(4) << p.getY() << "] " << setprecision(3) << p.getScalarValue() << endl;
}
This is used for printing on a text file.
ofstream& operator<<(ofstream &out, const Point2D &p){
return out << "[" << setw(4) << p.getX() << setw(1) << "," << setw(4) << p.getY() << "] " << setprecision(3) << p.getScalarValue() << endl;
}
Error:
Point.cpp:91:147: error: invalid initialization of reference of type ‘std::ofstream& {aka std::basic_ofstream&}’ from expression of type ‘std::basic_ostream::__ostream_type {aka std::basic_ostream}’

You do not need the second version. You can use the first:
Point p;
std::ofstream pointsFile("points.txt");
pointsFile << p << "\n";
First, The std::ostream& operator<< works for writing to files as well as writing to the standard output or stderrt
Second, assuming Poind2D inherits from Point, passing a Point2D to a function or operator that takes a Point reference will work too.

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) {...}

Use of ostream_iterator with an auto type?

In my college exam preparation I'm supposed to use ostream_operator with "auto" keyword.
Below is what I tried but the "auto" word is underlined in red with the error stating that `auto is not allowed here'.
I need auto here because the class attribute within the vector are of another class' type and is not recognized from within this current class.
ostream& operator<<(ostream& COUT, const Nastava& obj)
{
COUT << "<" << obj._datum << " - " << obj._satnica << "> <" << obj._prostorija << "> " << " <" << obj._predavac << "> " << obj._tipNastave;
COUT << endl << obj._predmet->Info();
ostream_iterator<auto> outit(COUT, "\n");
copy(obj._prisutni->begin(), obj._prisutni->end(), outit);
return COUT;
}

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;

C++ - Overloaded Operator in Derived Class not working

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.

using setw with user-defined ostream operators

How do I make setw or something similar (boost format?) work with my user-defined ostream operators? setw only applies to the next element pushed to the stream.
For example:
cout << " approx: " << setw(10) << myX;
where myX is of type X, and I have my own
ostream& operator<<(ostream& os, const X &g) {
return os << "(" << g.a() << ", " << g.b() << ")";
}
Just make sure that all your output is sent to the stream as part of the same call to operator<<. A straightforward way to achieve this is to use an auxiliary ostringstream object:
#include <sstream>
ostream& operator<<(ostream& os, const X & g) {
ostringstream oss;
oss << "(" << g.a() << ", " << g.b() << ")";
return os << oss.str();
}
maybe like so using the width function:
ostream& operator<<(ostream& os, const X &g) {
int w = os.width();
return os << "(" << setw(w) << g.a() << ", " << setw(w) << g.b() << ")";
}