Search code examples
c++istreamostream

C++ error unexplained: error: expected initializer before '&' token


i know there's a few other posts like this, but i've been on this single error for over an hour now and can't figure it out. here's the code that's giving trouble

istream& operator>>(istream& in, UndirectedGraph& g)
{
    int numVerticies;
    in >> numVerticies;
    g = UndirectedGraph(numVerticies);

    for(int i = 0; i < numVerticies; i++)
    {
        int temp;
        in >> temp;
        if(temp != i)
        {
            g.linkedAdjacencyList[i]->value = temp;
        }
    }

    int edges;
    in >> edges;
    g.edges = edges;
    for(int i = 0; i < edges; i++)
    {
        int first;
        int second;
        in >> first >> second;
        addEdge(first, second);
    }
    return in;
}

ostream& operator<<(ostream& out, UndirectedGraph& g)
{
    out << g.numVerticies << endl;

    for(int i = 0; i < g.numVerticies; i++)
    {
        out << g.linkedAdjacencyList[i] << " ";
    }
    out << endl;

    out << g.edges << endl;

    for(int i = 0; i < g.numVerticies; i++)
    {
        out << linkedAdjacencyList[i]->value;
        Node* whereto;
        whereto = linkedAdjacencyList[i]->adj;
        while(whereto->adj != NULL)
        {
            out << " " << whereto->value;
            whereto->adj = whereto->adj->adj;
        }
    }
    return out;
}

int main()
{

    ifstream inFile;
    inFile.open("hw8.in");

    UndirectedGraph graph;
    inFile >> graph;

...

here, the errors are on lines 1 and 28, with the overloading of istream and ostream.

Thanks for your help!


Solution

  • This:

    void UndirectedGraph::istream& operator>>(istream& in, UndirectedGraph g)
    

    doesn't make sense! You probably want:

    istream& operator>>(istream& in, UndirectedGraph g)
    

    Having said that, you don't seem to be returning anything in your function definition.