gpt4 book ai didi

c++ - 访问从成员函数返回的私有(private)嵌套类

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:16 29 4
gpt4 key购买 nike

请帮助我理解为什么类成员函数可以返回私有(private)嵌套类对象,以及为什么可以在该私有(private)嵌套类上调用成员函数,例如:

class Y
{
class X
{
public:
void f() { cout << "Hello World" << endl; }
};

public:
X g() { return X(); }
};

void h()
{
Y::X x; // Error, as expected: class Y::X is private.
x.f(); // Error.

Y y; // OK.
y.g().f(); // OK. But why???
}

我用 GCC 和 Visual C++ 进行了测试,最后一行在两者上都进行了编译。我似乎无法在 C++ 标准中找到任何使它有效的内容。知道为什么会这样吗?

编辑:

另一个观察:

void i()
{
Y y;

Y::X x2 = y.g(); // Error: class Y::X is private
x2.f(); // Error

auto x3 = y.g(); // OK
x3.f(); // OK
}

最佳答案

将嵌套类设为private 并不意味着外部作用域永远不能使用该类的实例。访问说明符会影响名称,并且您的main 函数永远不会尝试名称 Y::X1 Y::X 唯一被命名的地方是在 Y 中,它当然可以访问它自己的 private 成员。该函数将 Y::X 的实例返回给 main 并不是特别相关。

[C++14: 11/1]: A member of a class can be

  • private; that is, its name can be used only by members and friends of the class in which it is declared.
  • protected; that is, its name can be used only by members and friends of the class in which it is declared, by classes derived from that class, and by their friends (see 11.4).
  • public; that is, its name can be used anywhere without access restriction.

不可否认,该标准没有任何文本明确地让您消除疑惑,并指出对实体本身的访问不受这些关键字的控制,但这绝对是意图,并且最终就法律术语而言。

1 它确实命名为 Y::X::f,但该名称是 public

关于c++ - 访问从成员函数返回的私有(private)嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33197559/

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