简体   繁体   English

将节点作为外流操作符传递

[英]Passing a node as an outstream operator

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 friended in the Node class.注意:ostream 运算符在节点 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;
}

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 运算符,通常最好使用引用而不是指针:

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

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

Your overloaded stream operator declaration should be like this:您重载的 stream 运算符声明应如下所示:

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.您应该返回对std::ostream的 object 的引用, &被错误地放置在您重载的 function 原型中。

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.注意:为了便于演示,我将 class Node成员设为公开。

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM