我有一个带有构造函数和重载的 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::cout
是 std::ostream
而不是 std::ofstream
类型的全局对象。 std::ofstream
是 std::ostream
的派生物。参见 http://en.cppreference.com/w/cpp/io/cout
所以,修改你的友元函数(运算符)为
friend ostream & operator<<(ostream&, const Graph &);
关于c++ - 运算符 << 重载错误 - 未找到运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35832971/