c++ - 运算符 << 重载错误 - 未找到运算符

标签 c++ compiler-errors operator-overloading

我有一个带有构造函数和重载的 Graph 类 operator << , graph.h :

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

构造函数的定义(对于最小示例不重要)和运算符 << 在单独的文件中 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)

我没能自己找到代码中的错误,我将感谢您的每一条建议。

最佳答案

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

所以,修改你的友元函数(运算符)为

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

关于c++ - 运算符 << 重载错误 - 未找到运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35832971/

相关文章:

c++ - C std::lower_bound,使用重载运算符作为二进制谓词 comp?

c++ - 安全地重载流操作符>>

c++ - 模板类的赋值运算符

c++ - 理论或方向、c++、qt 和使用 MXE 进行交叉编译

c++ - glGenBuffers 访问冲突异常

asp.net-mvc - Razor 编译器警告/错误 - ASP.NET MVC 4

java - 如何使用构造函数来打印每本书的主题,颜色和页面?

Java 错误 : illegal start of expression

c++ - 他们是如何编写 MSVC++ Debugger 的?

android - 将 "-O0"添加到 cppFlags 无法在 android studio 中禁用 clang 编译优化