gpt4 book ai didi

c++ - 如果对 friend 应用访问控制怎么办?

转载 作者:搜寻专家 更新时间:2023-10-31 01:26:30 26 4
gpt4 key购买 nike

我正在阅读 C++11 标准 (N3092)。

11-4 成员(member)访问控制

Access control is applied uniformly to all names, whether the names are referred to from declarations or expressions. [ Note: access control applies to names nominated by friend declarations (11.4) and using- declarations (7.3.3). — end note ]

11.4-9 friend

A name nominated by a friend declaration shall be accessible in the scope of the class containing the friend declaration. The meaning of the friend declaration is the same whether the friend declaration appears in the private, protected or public (9.2) portion of the class member-specification.

由于我的英语水平很差,这两个摘录似乎并不一致。如第一个摘录中所示,如果将访问控制应用于 friend 会怎样?谁能给我一个具体的示例代码?


第一个摘录还谈到了 using 声明。这可以通过下面的代码确认。所以你可以说“访问控制肯定适用于 using 声明”。但是我不知道如何编写代码来查看访问受控的 friend 函数的行为。

#include <iostream>
using std::cout;

class B {
public:
void f() { cout << "B::f()\n"; }
void f(int) { cout << "B::f(int)\n"; }
};

class D : public B {
public:
using B::f; //`using` declaration in `public` context
void f() { cout << "D::f()\n"; }
};

class D2 : public B {
using B::f; //`using` declaration in `private` context
public:
void f() { cout << "D2::f()\n"; }
};

int main() {

D d;
d.f(); //=> "D::f()"
d.f(0); //=> "B::f(int)"

D2 d2;
d2.f(); //=> "D2::f()"
d2.f(0); //=> "error: ‘void B::f(int)’ is inaccessible within this context"

}

如上代码,如果我这样写

public:
friend void some_func() { }

,是否对名称 some_func 应用了访问控制?怎么办?

最佳答案

it seems these two excerpts aren't consistent

它们是一致的,但并非必须如此。 [note: ] 中的任何内容 block 是非规范文本。它用于为人类目的总结某些东西或提供澄清示例,但不用于定义语言的实际行为。所以唯一真正重要的摘录是第二个。

第一个摘录中的粗体文本是在谈论好友声明的内容。如果你有两个类(class),AB ,并且您想成为 B 的特定成员A的 friend , 粗体文字表示您指定的特定成员必须已经可以通过 A 访问.也就是说,这是非法的:

class B
{
private:
void SomeMember();
};

class A
{
private:
friend void B::SomeMember(); //`SomeMember` is not accessible to `A`, so ill-formed.
};

B必须让自己成为A的 friend ,所以 A可以命名其私有(private)成员。

第二个摘录中的粗体文本仅表示 friend 所在的位置声明发生在一个类中并不重要。 friend 没关系声明是公开的、私有(private)的或其他。也就是说,以下所有内容都表示同一件事:

class B;

class A1
{
public:
friend class B;
};

class A2
{
protected:
friend class B;
};

class A3
{
private:
friend class B;
};

所以这两个加粗的摘录彼此没有任何关系。

现在,第二个 except 的未加粗部分实际上用规范语言表达了第一个摘录中的符号所说的内容。即,在 friend 中指定的名称声明必须是可访问的。

if I write <...> is access control applied to the name some_func? How?

没关系。 friend 定义 总是定义非成员函数。因此,它们不在类的范围内,因此它们实际上是 public .因此易于访问。

关于c++ - 如果对 friend 应用访问控制怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55313944/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com