gpt4 book ai didi

c++ - 继承层次结构中的成员访问 - C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:36:18 24 4
gpt4 key购买 nike

struct A {
protected:
int y;
public:
int z;
};

struct F : A {
public:
using A::y;
private:
using A::z;
};

int main() {
F obj_F;
obj_F.y = 9;
obj_F.z = 10;
}

来源: http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/index.jsp?topic=/com.ibm.vacpp7a.doc/language/ref/clrc14cplr135.htm

在上面的代码中 obj_F.z = 10; - 是允许的。解释:成员 z 的访问权限仍然是公开的。使用 A::z 的私有(private) using 声明对 z 的访问没有影响。

谁能告诉我,如果声明为private的z对外是可以访问的,那么那个private是什么意思呢?它有什么作用?

谢谢

-赛亚索达兰

最佳答案

根据标准代码是有效的 - 看到这个标准规则,我之前回答的时候没有想到

A member m is accessible when named in class N if

  • [...], or
  • there exists a base class B of N that is accessible at the point of reference, and m is accessible when named in class B.

这完全适用于您的代码,因此访问是有效的...这条规则的主要目的似乎是允许基类的友元声明适用于继承的成员,但它也适用于这种情况。


(忽略这部分说代码无效的部分 - 它如上所述有效。这部分是我答案的旧版本,保留在这里作为背景信息)

不,此代码无效。这就是为什么以这种方式调用等效的“访问声明”(尽管这些已被弃用)

struct F : A {
public:
A::y;
private:
A::z;
};

这些被称为“访问声明”正是因为它们可以更改访问...在您的示例中,命名类是 Fz 作为 F 的成员是私有(private)的,因为 using 声明确实更改了名称 z 的访问级别。

关于c++ - 继承层次结构中的成员访问 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3741514/

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