2015-11-06 44 views
-1

我有一個簡單的Node類,它創建節點並可以訪問這些節點內的字符串。爲了能夠比較節點(> overloader)並打印其數據(< < overloader),該類中有兩個運算符重載函數。還有內置的max()函數的模板副本。我的兩個操作員超載工作正常,除非我嘗試以兩個節點作爲參數打印max()函數的返回值。這裏是我的代碼:在函數的返回值上使用運算符時,運算符重載函數不起作用

#include <iostream> 
#include <vector> 
using namespace std; 

template<typename T> 
T maximum(const T& a, const T& b){ 
    return a > b ? a : b; 
} 

class Node{ 
public: 
    Node(const string& s = "Default"): 
     data(s){ 

    } 

    string get_data() const { 
     return this->data; 
    } 

    friend ostream& operator << (ostream& os, Node& a){ 
     return os << a.get_data(); 
    } 

    friend bool operator > (const Node& a, const Node& b){ 
     if(a.get_data() > b.get_data()){ 
      return true; 
     } 
     else return false; 
    } 

private: 
    string data; 
    Node* next; 
}; 

int main() { 

    double d1 = 0.1, d2 = 0.2; 
    cout << maximum(d1, d2) << endl; 

    string s1 = "woody", s2 = "buzz"; 
    cout << maximum(s1, s2) << endl; 

    Node a("buzz"), b("woody"); 
    cout << maximum(a, b) << endl; 

    return 0; 
} 

問題出在main()函數的最後一行。我的編譯器會引發錯誤消息,類似的東西cannot bind ostream<char> value to ostream<char>&&

回答

1

添加constoperator<<秒參數:

friend ostream& operator << (ostream& os, const Node& a){ 
              ^^^^^