运算符错误<<重载 - 找不到运算符

时间:2016-03-06 21:41:54

标签: c++ compiler-errors operator-overloading

我有一个带有构造函数的图表,并且已经重载operator <<graph.h

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

构造函数的定义(对于最小示例而言不重要)和运算符&lt;&lt;在分开的文件graph.cpp中:

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

当我尝试在operator <<中致电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;
}

我收到错误

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

我没有设法自己在代码中找到错误,我会感谢每一条建议。

1 个答案:

答案 0 :(得分:1)

std::coutstd::ostream而非std::ofstream类型的全局对象。 std::ofstreamstd::ostream的衍生物。见http://en.cppreference.com/w/cpp/io/cout

因此,请将您的朋友功能(操作员)修改为

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