E.Brown
E.Brown

Reputation: 29

Error in operator << overloading - no operator found

I have a class Graph with constructor and overloaded operator <<, graph.h:

class Graph
{
    private:
        vector<int> setOfVertices;
    public:
        Graph(ifstream &);      //konstruktor ze souboru
        friend ofstream & operator<<(ofstream&, const Graph &);
};

the definition of constructor(not important for minimal example) and operator << are in separated file graph.cpp:

ofstream & operator<<(ofstream& outputStream, const Graph & graphToPrint)
{
    //not important for minimal example
    return outputStream;
}

When I try to call operator << in main.cpp:

#include <iostream>
#include <fstream>
#include "graph.h"

using namespace std;

int main()
{
    ifstream myFile ("example.txt");
    Graph * G = new Graph(myFile);
    cout << *G;
    return 0;
}

I get an error

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Graph' (or there is no acceptable conversion)

I didn't manage to locate the mistake in the code by myself, I will be thankful for every piece of advice.

Upvotes: 1

Views: 102

Answers (1)

WhiZTiM
WhiZTiM

Reputation: 21576

std::cout is a global object of type std::ostream not std::ofstream. std::ofstream is a derivative of std::ostream. See http://en.cppreference.com/w/cpp/io/cout

So, modify your friend function (operator) to

friend ostream & operator<<(ostream&, const Graph &);

Upvotes: 1

Related Questions