gpt4 book ai didi

c++ - friend 库功能可以访问子数据

转载 作者:行者123 更新时间:2023-11-30 03:21:12 25 4
gpt4 key购买 nike

class Child;

class Base
{
friend bool friendly(const Base&,const Child&) ;
private:
std::string name;
public:
Base() {}
};

class Child: public Base
{
private:
int number;

public:
Child() {}

};



bool friendly(const Base &base, const Child &child )
{

return base.name== child.name;
}

我没有使用其他类型。我实际上是在传递 Child 和 Base 对象来调用一个函数。

friend(Base(),Child());

我不太明白为什么 Child 可以访问 name 变量。访问数字成员变量时:{child.number} 使用友好函数编译器生成编译错误“私有(private)数据”。为什么我看不到名称变量的错误。它们有不同的类型!

P.S.:我认为这是非常糟糕的设计。我很关心 C++11 的这种特殊行为。

最佳答案

我认为您是对的,这种行为不是特别直观,特别是因为您通常无法访问基类的私有(private)成员。但它不应该是一个编译错误,因为这种情况实际上在 C++14 ISO 标准中提到(第 11.2.5 节,由您真正完成的粗体):

5) If a base class is accessible, one can implicitly convert a pointer to a derived class to a pointer to that base class (4.10, 4.11). [ Note: It follows that members and friends of a class X can implicitly convert an X* to a pointer to a private or protected immediate base class of X. — end note ] The access to a member is affected by the class in which the member is named. This naming class is the class in which the member name was looked up and found. [ Note: This class can be explicit, e.g., when a qualified-id is used, or implicit, e.g., when a class member access operator (5.2.5) is used (including cases where an implicit “this->” is added). If both a class member access operator and a qualified-id are used to name the member (as in p->T::m), the class naming the member is the class denoted by the nested-name-specifier of the qualified-id (that is, T). — end note ] A member m is accessible at the point R when named in class N if

(5.1) — m as a member of N is public, or

(5.2) — m as a member of N is private, and R occurs in a member or friend of class N, or

(5.3) — m as a member of N is protected, and R occurs in a member or friend of class N, or in a member or friend of a class P derived from N, where m as a member of P is public, private, or protected, or

(5.4) — there exists a base class B of N that is accessible at R, and m is accessible at R when named in class B

它遵循上面的 blub 和这个例子:

class B;
class A {
private:
int i;
friend void f(B*);
};
class B : public A { };
void f(B* p) {
p->i = 1; // OK: B* can be implicitly converted to A*,
// and f has access to i in A
}

您没有使用指针,但 const 引用也可以隐式转换。

关于c++ - friend 库功能可以访问子数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52240516/

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