【发布时间】:2021-06-28 14:31:21
【问题描述】:
考虑以下程序:
#include <iostream>
using namespace std;
class B;
class A {
int a;
public:
A():a(0) { }
void show(A& x, B& y);
};
class B {
private:
int b;
public:
B():b(0) { }
friend void A::show(A& x, B& y);
};
void A::show(A& x, B& y) {
x.a = 10;
cout << "A::a=" << x.a << " B::b=" << y.b;
}
int main() {
A a;
B b;
a.show(a,b);
return 0;
}
在这个问题上让我感到困惑的是,在 A 类内部,我们没有将函数 show 声明为 A 类的友元函数。那么我们如何在show() 函数的定义?
按照我的说法,如果以这种方式定义,show 函数将是 A 类的友元函数:
friend void show(A& x, B& y);
请指导。
【问题讨论】:
-
show()是类A的成员,因此它可以访问类A的所有实例的所有成员。一个类的private成员可以访问该类的所有成员函数,或者该类的friends。 -
许多新的 C++ 程序员的困惑是认为
private字段意味着this实例的成员(就像在现实生活中一样)。private或protected属性适用于每个类,而不是每个实例。