2014-04-27 160 views
2

我試圖超載< <。到目前爲止沒有運氣。 這裏是我的過載實現:未能超載運算符<<(C++)

struct Engineer{ 
    int id; 
    int salary; 
    bool hired; 
public: 
    Engineer(int _id, int _salary) : id(_id), salary(_salary), hired(false) {} 

    std::ostream& operator<<(std::ostream& os) 
    { 
     return os << " " << id << std::endl; 
    } 
}; 

,這裏是我嘗試使用它:

void inorderTravel(AvlNode* root) { 
    if(root == NULL) return; 
    inorderTravel(root->left); 
    std::cout << root->data;  // <- here 
    inorderTravel(root->right); 
} 

行了 「的std ::法院< <根 - >數據;」喚起所有錯誤:

> Multiple markers at this line 
> - cannot convert 'root->AvlTree<Engineer, IdKey>::AvlNode::data' (type 'Engineer') to type 'unsigned char' 
> - cannot convert 'root->AvlTree<Engineer, IdKey>::AvlNode::data' (type 'Engineer') to type 'signed char' 
> - 'Engineer' is not derived from 'const std::basic_string<_CharT, _Traits, _Alloc>' 
> - cannot convert 'root->AvlTree<Engineer, IdKey>::AvlNode::data' (type 'Engineer') to type 'char' 
> - deduced conflicting types for parameter '_CharT' ('char' and  'Engineer') 
> - no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'Engineer') 
> - candidates are: 
> - cannot convert 'root->AvlTree<Engineer, IdKey>::AvlNode::data' (type 'Engineer') to type 'const char*' 
> - mismatched types 'const _CharT*' and 'Engineer' 
> - cannot convert 'root->AvlTree<Engineer, IdKey>::AvlNode::data' (type 'Engineer') to type 'const unsigned char*' 
> - cannot convert 'root->AvlTree<Engineer, IdKey>::AvlNode::data' (type 'Engineer') to type 'const signed char*' 
+0

什麼是'AvlNode'的定義是什麼? –

+0

什麼是'root-> data'? – 0x499602D2

+0

[運算符重載]的可能重複(http://stackoverflow.com/questions/4421706/operator-overloading) –

回答

1

這不是operator<<的正確定義。此運算符應該爲參數爲您試圖打印的類的實例的const引用。使用你的定義有一個隱含的第一個的論點。一個operator<<不能在一個類中定義,通常它被實現爲一個朋友函數。事情是這樣的:

struct Engineer{ 
    //... other code 
    friend std::ostream& operator<<(std::ostream& os, const Engineer& e); 
}; 

std::ostream& operator<<(std::ostream& os, const Engineer& e) 
{ 
    return os << " " << id << std::endl; 
} 
+0

非常感謝!它一直在竊聽我幾個小時! –

+0

*運算符<<不能在類中定義* - 這是全部真相嗎?如果是的話,爲什麼? – Wolf

+0

@wolf從OP的問題來看,這個想法是使用'operator <<'輸出到一個流。如果這是需要的,應按我描述的方式聲明運營商。這意味着這個運算符的第一個參數應該是一個'ostream&',並且所有的類方法都有一個類類型的隱式第一個參數,所以不可能在類中聲明這樣的方法。具有其他操作數類型的'operator <<'仍可以聲明,但在OP描述的情況下不會使用它。 –

2

您定義的操作符std::ostream& Engineer::operator<<(std::ostream&) - 所以像left << right表達式的左操作數必須是Engineer類型和std::ostream&類型的右操作數的...

您可以定義權運營商在你的Engineer類友元函數,像這樣:

friend std::ostream& operator<<(std::ostream& out, Engineer const& self) 
{ return out << " " << self.id << std::endl; } 
+0

*左邊的參數*似乎有點誤導性 – Wolf

+0

@Wolf澄清了含義 –

+0

更改順序如何解決方法:先解決方法,稍後再解決失敗的方法?我發現重點在於[當前版本的答案](http://stackoverflow.com/revisions/23325060/2)中的錯誤。 – Wolf