重载流插入运算符错误,无法编译

overloaded stream insertion operator errors, won't compile

本文关键字:编译 错误 插入 运算符 重载      更新时间:2023-10-16

我试图重载operator<<为我的Graph类,但我不断得到各种错误:

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2143: syntax error : missing ',' before '<'

我将operator<<的原型放置在Graph类定义的正上方。operator<<的定义位于文件的最底部。错误是否与头部警卫有关?

Graph.h:

#ifndef GRAPH
#define GRAPH
#include <iostream>
#include <vector>
#include <map>
#include <sstream>
#include "GraphException.h"
#include "Edge.h"
using namespace std;
template <class VertexType>
ostream& operator<<( ostream& out, const Graph<VertexType>& graph );
/** An adjacency list representation of an undirected,
 * weighted graph. */
template <class VertexType>
class Graph
{
    friend ostream& operator<<( ostream& out, const Graph& graph );
   // stuff
}  

template <class VertexType>
ostream& operator<<( ostream& out, const Graph<VertexType>& graph )
{
    return out;
}
#endif GRAPH

main:

#include <iostream>
#include "Graph.h"
using namespace std;
const unsigned MAX_NUM_VERTICES = 9;
int main()
{
    // create int graph:
Graph<int> iGraph( MAX_NUM_VERTICES );
    // add vertices and edges
    cout << iGraph;

    return 0;
}

operator<<的声明缺少Graph的声明。一种解决方案是在operator<<声明之前声明类:

template <class VertexType>
class Graph;

或者可以在类之外完全省略operator<<的声明,因为friend声明也构成了operator<<的非成员声明。