2011-07-17 16 views
0

這會打印有關限定符的錯誤消息,但並不真正理解這意味着什麼以及如何調整代碼以使其工作?無論如何,非常感謝您查看代碼。將節點作爲流出運營商傳遞

注意:ostream運算符在節點類中有好處。

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

所以從這個角度來看它是不可能的?是否最好從節點函數本身依次調用它們中的每一個呢? –

回答

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

內使用currentNode-> getFirstName()我使用命名空間std,是否清除它?對不起,我沒有在代碼中提到這一點。 –

+0

@Jason A.:看到編輯的答案,添加了一個可編輯的工作副本,你正試圖達到目的。 –

+0

是的。非常感謝!對此,我真的非常感激! –

0

對操作的返回值的&是在錯誤的地方,這是通常最好使用引用,而不是指針ostream的運營商:

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

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

希望我可以使用參考,但我沒有選擇。我非常欣賞代碼,但是當我嘗試使用currentNode參數調用項目時出現了相同的錯誤。 –

+0

如果您發佈了實際的錯誤消息,這將有所幫助。 – Sven

+0

通過âconstNodeâ作爲â€「字符串的âthisâ參數Node :: getFirstName()â丟棄限定符 –