【问题标题】:overloaded stream insertion operator errors, won't compile重载流插入运算符错误,无法编译
【发布时间】:2013-05-05 06:24:52
【问题描述】:

我正在尝试为我的Graph 类重载operator<<,但我不断收到各种错误:

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

我将operator&lt;&lt; 的原型放在Graph 类定义的正上方。 operator&lt;&lt; 的定义位于文件的最底部。这些错误是否与标头保护有关?

这里是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;
}

【问题讨论】:

  • 如果您尝试创建SSCCE,将来人们会更有帮助。以这种方式思考的一个很好的副作用是,您可能会在发布问题之前弄清楚您的问题。
  • 谢谢,我不知道 SSCCE。我删掉了所有我觉得无关紧要的东西。问题是,我通常不是无关紧要和无关紧要的最佳仲裁者。
  • 这是一个整数图。编辑它。

标签: c++ operator-overloading


【解决方案1】:

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

template <class VertexType>
class Graph;

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

【讨论】:

  • 删除运算符
  • @JamesGold:抱歉,我手头没有 Visual Studio。我的两个建议都适用于 Apple Clang 4.2 和 GCC 4.2.1。你也可以试试template&lt;class V&gt; friend ostream&amp; operator&lt;&lt;(ostream&amp;, const Graph&lt;V&gt;&amp;);——也就是说,声明operator&lt;&lt;Graph&lt;VertexType&gt;的朋友,对于任何V,而不仅仅是VertexType
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-10
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 2016-07-09
  • 1970-01-01
相关资源
最近更新 更多