将节点作为流出运算符传递

时间:2011-07-17 05:17:09

标签: c++ ostream this-pointer

这会打印关于限定符的错误消息,但是不能真正理解这意味着什么以及如何调整代码以使其起作用?无论如何,非常感谢您查看代码。

注意:ostream运算符在Node类中有用。

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

2 个答案:

答案 0 :(得分:0)

运算符返回值的&位置错误,通常使用引用而不是ostream运算符的指针更好:

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

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

答案 1 :(得分:0)

您的重载流操作符声明应如下所示:

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

您应该返回对std::ostream对象的引用,&错误地放在您重载的函数原型中。

查看工作示例 here

在此处添加源代码,以确保完整性 注意:为了便于演示,我已将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;
}