arunoruto
arunoruto

Reputation: 278

Bunch of errors while overloading the output operator

I have been writing a code and wanted to overload the << operator. To do so I declared the operator as a friend function so it has access to some private variables which should stay private! But it's giving me a lot of errors back. What gives me the most problems is that it does not allow me to access those private data which I need. If I comment out the operator the programm compiles just fine. And sorry because the language in the code is German.

Header:

#pragma once
class fahrzeug
{
private:
    int hg;
    double tank;
    double fst;
    double dsv;
    double ks;
public:
    fahrzeug();
    fahrzeug(const fahrzeug& brm);
    friend ostream& operator<<(ostream& os, const fahrzeug& obj); // <------
    ~fahrzeug();
};

CPP:

#include "fahrzeug.h"
#include <iostream>
using namespace std;



fahrzeug::fahrzeug()
{
    hg = 180;
    tank = 50;
    fst = 45;
    dsv = 9;
    ks = 50000;
}

fahrzeug::fahrzeug(const fahrzeug& brm)
{
    hg = brm.hg;
    tank = brm.tank;
    fst = brm.fst;
    dsv = brm.dsv;
    ks = brm.ks;
}

ostream& operator<<(ostream& os, const fahrzeug& brm) // <------ Operator
{
    os << "Höchstgeschwindigkeit: " << brm.hg << "km/h." << endl;
    os << "Volumen des Tanks: " << brm.tank << "L." << endl;
    os << "Füllstand des Tanks: " << brm.fst << "L." << endl;
    os << "Durchschnittlicher Spritverbrauch: " << brm.dsv << "L/(100km)" << endl;
    os << "Kilometerstand des Fahrzeugs: " << brm.ks << "km." << endl;

    return os;
}

fahrzeug::~fahrzeug()
{
}

Upvotes: 0

Views: 37

Answers (1)

R Sahu
R Sahu

Reputation: 206667

You forgot to #include <iostream> in fahrzeug.h.

Add

#include <iostream>
using std::ostream;

right after

#pragma once

Upvotes: 3

Related Questions