我有一个带有构造函数的图表,并且已经重载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)
我没有设法自己在代码中找到错误,我会感谢每一条建议。
答案 0 :(得分:1)
std::cout
是std::ostream
而非std::ofstream
类型的全局对象。 std::ofstream
是std::ostream
的衍生物。见http://en.cppreference.com/w/cpp/io/cout
因此,请将您的朋友功能(操作员)修改为
friend ostream & operator<<(ostream&, const Graph &);