‘friend’声明会影响基类成员的可访问性吗?

huangapple go评论146阅读模式
英文:

Does 'friend' declaration affect the accessibility of members in the Base class?

问题

在第一个示例中,Base 中的 friend 声明使得在 main() 函数中,d.jd.k 不会导致错误。然而,在第二个示例中,friend 声明似乎没有任何影响。编译器在 main() 中对 d.id.jd.kd.m 以及 d.n 都会抛出错误。

第一个示例中,publicprotected 继承是起作用的。

英文:

I am confused on the effectiveness of a friend declaration.

In the first example, this friend declaration in Base caused me to not get an error on d.j and d.k in the main() function.

However, in the second example, it seems the friend declaration has no impact at all. The compiler throws errors in main() on d.i, d.j, d.k as well as d.m and d.n.

It seems public and protected inheritance only matters.

Example 1:

struct Base
{
	friend int main(); 

public:
	int i;

protected:
	int j;

private:
	int k;
};

struct Derived : public Base
{
public:
	int l;
protected:
	int m;
private:
	int n;
};

int main()
{
	Derived d; 
	d.i = 1;
	d.j = 2;
	d.k = 3;
	d.l = 4;
	d.m = 5; //error
	d.n = 6; //error

	return 0;
}

Example 2:

struct Base
{
	friend int main(); 

public:
	int i;

protected:
	int j;

private:
	int k;
};

struct Derived : protected Base
{
public:
	int l;
protected:
	int m;
private:
	int n;
};

int main()
{
	Derived d; 
	d.i = 1; //error
	d.j = 2; //error
	d.k = 3; //error
	d.l = 4;
	d.m = 5; //error
	d.n = 6; //error

	return 0;
}

答案1

得分: 2

d.i 是虚构的。Derived 中没有 i。它确实有一个 Base,而 Base 本身有一个 i。因此,要访问 d.i,首先必须能够看到 Derived::Base

如果你公开继承自一个基类,那意味着任何代码都可以看到派生类的基类对象。如果你以保护方式继承自一个基类,只有具有对派生类的保护访问权限的代码才能看到派生类的基类对象。

mainBase 的友元,而不是 Derived 的友元。因此,它对 Derived 没有特殊访问权限。因此,如果你使用保护继承,它无法访问 Derived::Base,因此也无法看到 Derived::Base::i

英文:

d.i is a fiction. Derived does not have i in it. What it does have is a Base, which itself has an i in it. To get to d.i therefore, one must first be able to see Derived::Base.

If you publicly inherit from a base class, that means any code can see the derived class's base class object. If you protectedly inherit from a base class, only code with protected access to the derived class can see the derived'd class's base class object.

main is a friend of Base, not Derived. So it has no special access to Derived. Therefore, if you use protected inheritance, it cannot get to Derived::Base and therefore cannot see Derived::Base::i.

huangapple
  • 本文由 发表于 2023年3月4日 07:24:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定