Operator overloading in header files and in the cpp files

24,929

Solution 1

The operator is not a member of the class, it is a friend so

 ostream& Hallgato::operator<<(ostream& output, const Hallgato& H) {

should be

 ostream& operator<<(ostream& output, const Hallgato& H) {

also to be able to use the operator from other files you should add a prototype into the header file.

The header file would become this

hallgato.h

#ifndef HALLGATO_H
#define HALLGATO_H

#include<iostream>
#include<string>

class Hallgato {
    private:
        char* nev;
        char* EHA;
        int h_azon;
        unsigned int kepesseg;
    public:
        friend std::ostream& operator<<(std::ostream& output, const Hallgato& H);
};

std::ostream& operator<<(std::ostream& output, const Hallgato& H);

#endif /* End of HALLGATO_H */

Somewhere in a ".cpp" file you would implement the operator function, you can also do it in the header file but then you would have to recompile often with some compilers.

hallgato.cpp

#include "hallgato.h"

std::ostream& operator<<(std::ostream& output, const Hallgato& H) 
{
   /* Some operator logic here */
}

NOTE: When you modify header files, many compilers usually do not re-include them in your .cpp files. This is done to avoid unnecessary recompilation. To force a re-include, you have to make some modifications(delete empty line) to the source files which include those headers or force recompilation in your compiler/IDE.

Solution 2

In header file you declared friend method for class

friend ostream& operator<<(ostream& output, const Hallgato& H);

this method shoud be defined (in cpp) without Hallgato::

ostream& operator<<(ostream& output, const Hallgato& H)

because this method is not part of Hallgato class.

Share:
24,929
B.J
Author by

B.J

Updated on July 05, 2022

Comments

  • B.J
    B.J almost 2 years

    I got an error, when I am trying to overload an operator.

    My header file:

    #include<iostream>
    #include<string>
    using namespace std;
    
    #ifndef HALLGATO_H
    #define HALLGATO_H
    
    class Hallgato {
        private:
            char* nev;
            char* EHA;
            int h_azon;
            unsigned int kepesseg;
        public:
            friend ostream& operator<<(ostream& output, const Hallgato& H);
    };
    #endif
    

    My cpp file:

    #include<iostream>
    #include "Hallgato.h"
    using namespace std;
    
        ostream& Hallgato::operator<<(ostream& output, const Hallgato& H) {
            output << "Nev: " << H.nev << " EHA: " << H.EHA << " Azonosito: " << H.h_azon << " Kepesseg: " << H.kepesseg << endl;
            return output;
        }
    };
    

    In my .cpp file, when I want to define the overloaded operator <<, I got an error. Why?

  • Karan
    Karan over 6 years
    Rebuild all the files again if you are using Dev-C++ 5.11 (Windows x64). Took my hour on this.