2010-07-17 73 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,因为这个名字已经代表一个类型。)