我搜索了很多关于我无法理解的内容,但是我对于“朋友”和非成员功能存在的一些困难并没有找到合适的答案。所以,在这里它是...朋友和非成员功能困境
这是一个示例代码,其模式类似于相应的代码,我看到:
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”变量?
我无法理解你的意思。 'foo2'显然是公开的。尝试输入'rhs.bar = 5;'而不是'rhs.foo2();'然后你会看到不同之处。 – PeterT
请包括您感到困惑的代码。因为这里似乎没有问题。 ('bar',唯一的'私人'的东西,永远不会被访问。) – Potatoswatter