2013-07-27 52 views
-1

我搜索了很多关于我无法理解的内容,但是我对于“朋友”和非成员功能存在的一些困难并没有找到合适的答案。所以,在这里它是...朋友和非成员功能困境

这是一个示例代码,其模式类似于相应的代码,我看到:

struct SampleClass 
{ 
    friend void foo1(SampleClass &rhs); 
    void foo2(); 
private: 
    int bar; 
}; 

void foo1(SampleClass& rhs) 
{ 
    rhs.foo2(); 
} 

void foo3(SampleClass& rhs) 
{ 
    rhs.foo2(); 
} 

int main() 
{ 
    SampleClass samp; 
    foo1(samp); //friend function 
    foo3(samp); //not a friend function but has the same effect 
    return 0; 
} 

为什么我们如何使用它是确定的“朋友非成员函数类“关键字是不是类似的功能?为什么不知道“朋友”函数或类可以访问主机类的私有成员,第一个函数(“朋友”函数)访问“bar”变量?

+0

我无法理解你的意思。 'foo2'显然是公开的。尝试输入'rhs.bar = 5;'而不是'rhs.foo2();'然后你会看到不同之处。 – PeterT

+0

请包括您感到困惑的代码。因为这里似乎没有问题。 ('bar',唯一的'私人'的东西,永远不会被访问。) – Potatoswatter

回答

3

函数协议需要匹配。变化:

friend void foo1(); 

要:

friend void foo1(SampleClass& rhs); 
+0

这是正确的,但仍然不能解决我的问题 – atoipowered

+0

@ atoi.powered你是什么意思有同样的影响,void foo2()是一个公共函数... –

+0

你在哪里定义foo2(),你可以发布一些代码? –