开发者

Passing a node as an outstream operator

开发者 https://www.devze.com 2023-03-21 06:56 出处:网络
This prints an error message about qualifiers but don\'t really understand what that means and how to adjust the code for it to work? Anyways, thanks a lot for looking at the code.

This prints an error message about qualifiers but don't really understand what that means and how to adjust the code for it to work? Anyways, thanks a lot for looking at the code.

Note: The ostream operator is fri开发者_Go百科ended in the Node class.

using namespace std;

ostream& operator(ostream& output, const Node* currentNode)
{
   return output;
}

void Node::nodeFunction()
{
   //This node has items attached to the 'this' statement. After
   //the necessary functions, this is called to output the items.

   cout << this;
}


Your overloaded stream operator declaration should be like this:

std::ostream& operator<<(std::ostream& os, const T& obj);
^^^^^^^^^^^^^

You should be returning a reference to object of std::ostream, the & is wrongly placed in your overloaded function prototype.

Have a look at the working sample here.

Adding the source code here, for completeness.
Note: I have taken class Node members as public for ease of demonstration.

#include<iostream>

using namespace std;

class Node
{
    public: 
    int i;
    int j;
    void nodeFunction();

    friend ostream& operator <<(ostream& output, const Node* currentNode);     
};

ostream& operator<<(ostream& output, const Node* currentNode)
{
   output<< currentNode->i;
   output<< currentNode->j;

   return output;
}

void Node::nodeFunction()
{
   //This node has items attached to the 'this' statement. After
   //the necessary functions, this is called to output the items.

   cout << this;
}

int main()
{
    Node obj;
    obj.i = 10;
    obj.j = 20;

    obj.nodeFunction();

    return 0;
}


The & on the return value of the operator is in the wrong place, and it's generally better to use references rather than pointers for ostream operators:

ostream& operator<<(ostream &output, const Node &currentNode)
{
    // Output values here.
    return output;
}

void Node::nodeFunction()
{
     cout << *this;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号