2010-07-17 141 views
9

朋友職能應該能夠訪問班級私人會員嗎? 那麼,我在這裏做錯了什麼?我已經將我的.h文件包含在運營商< <我打算與班級交朋友。有班級但不能訪問私人會員的朋友

#include <iostream> 

using namespace std; 
class fun 
{ 
private: 
    int a; 
    int b; 
    int c; 


public: 
    fun(int a, int b); 
    void my_swap(); 
    int a_func(); 
    void print(); 

    friend ostream& operator<<(ostream& out, const fun& fun); 
}; 

ostream& operator<<(ostream& out, fun& fun) 
{ 
    out << "a= " << fun.a << ", b= " << fun.b << std::endl; 

    return out; 
} 

回答

12

在這裏...

ostream& operator<<(ostream& out, fun& fun) 
{ 
    out << "a= " << fun.a << ", b= " << fun.b << std::endl; 

    return out; 
} 

你需要

ostream& operator<<(ostream& out, const fun& fun) 
{ 
    out << "a= " << fun.a << ", b= " << fun.b << std::endl; 

    return out; 
} 

(我一直咬了這個無數次的屁股,你的運算符重載的定義沒有按」 t完全符合聲明,所以它被認爲是不同的功能。)

+2

這很有趣,最簡單了事情怎麼會是最最難找到... – starcorn 2010-07-17 10:26:05

+0

是否'樂趣&'總是有是'const'? – peter 2017-01-02 07:38:32

5

簽名不匹配。你的非會員功能取笑&好玩,朋友聲明上帶const玩樂&好玩。

0

您可以通過編寫類定義友元函數定義避免這些類型的錯誤:

class fun 
{ 
    //... 

    friend ostream& operator<<(ostream& out, const fun& f) 
    { 
     out << "a= " << f.a << ", b= " << f.b << std::endl; 
     return out; 
    } 
}; 

的缺點是,對每operator<<調用內聯,這可能會導致代碼膨脹。

(另請注意,參數不能被稱爲fun,因爲這個名字已經代表一個類型。)